Abstract class and Interface in python

 n Python, there is no official interface keyword like in Java or C#. Instead, we use Abstract Base Classes (ABCs) via the abc module to create both abstract classes and "formal interfaces".

1. Abstract Class vs. Interface in Python
  • Abstract Class: A "blueprint" that cannot be instantiated and can contain both implemented (concrete) methods and unimplemented (abstract) methods.
  • Interface: In Python, this is essentially an abstract class where all methods are marked with @abstractmethod and contain no implementation (only pass).
2. What Can Be Included
FeatureAbstract ClassInterface (ABC)Description
Abstract MethodYesYesDefined using the @abstractmethod decorator; must be overridden by subclasses.
Constructor (__init__)YesNo (usually)Can hold shared initialization logic. While technically possible in interfaces, they usually don't have state.
Default/Concrete MethodYesNoStandard methods with code. Interfaces should only declare signatures without implementation.
Static/Class MethodYesYesCan use @staticmethod or @classmethod. These can also be marked as abstract.
Private VariablesYesNoUse double underscores (e.g., __var). These are often used in abstract classes to manage internal state.
PropertiesYesYesUse @property combined with @abstractmethod to enforce getters/setters in subclasses.
3. Usage Details
  • Decorators: The @abstractmethod decorator is the core tool. It can be stacked with others, such as @classmethod @abstractmethod.
  • Private Variables: Python uses Name Mangling for variables starting with __. These cannot be accessed directly by subclasses, allowing the abstract class to hide internal details.
  • Static Methods: Use @staticmethod for utility functions that don't need access to class or instance state.
  • Constructors: If an abstract class defines an __init__, subclasses must call it using super().__init__() if they want to benefit from that shared setup.
Would you like to see a code example demonstrating how to stack these decorators and manage private variables in a single abstract class?
  • Abstract Classes in Python
    3 Sept 2025 — In Python, an abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes...
    GeeksforGeeks·GeeksforGeeks
    7:04
  • Implementing an Interface in Python
    10 Feb 2020 — Python Interface Overview. At a high level, an interface acts as a blueprint for designing classes. Like classes, interfaces defin...
    Real Python
  • Abstract Class vs Interface| OOP, Python, C+ | Software Engineering
    21 Feb 2024 — This abstraction not only enhances code readability but also promotes code reusability, which is a critical aspect of modern softw...
    QuickStart
Show all
explain with example
In Python, you use the 
abc (Abstract Base Classes) module to create both abstract classes and interfaces.
Python Abstract Class Implementation
An abstract class can contain a mix of abstract methods (enforced for subclasses) and concrete methods (shared code).
python
from abc import ABC, abstractmethod

class BaseMachine(ABC):
    def __init__(self, brand):
        self.brand = brand      # Constructor with shared state
        self.__serial = "123"   # Private variable (name mangled)

    @abstractmethod
    def start(self):
        """Abstract Method: Subclasses MUST implement this."""
        pass

    def maintenance_msg(self):
        """Concrete/Default Method: Subclasses can use this directly."""
        return f"Checking {self.brand} machine health."

    @staticmethod
    def general_info():
        """Static Method: Utility not tied to instance state."""
        return "Machines require regular service."

    @property
    @abstractmethod
    def power_usage(self):
        """Abstract Property: Enforces a getter in subclasses."""
        pass
Use code with caution.
Python Interface Implementation
formal interface in Python is simply an abstract class where all methods are abstract and no state (like __init__) is maintained.
python
class IPaymentProcessor(ABC):
    @abstractmethod
    def process_payment(self, amount):
        pass

    @abstractmethod
    def refund(self, transaction_id):
        pass
Use code with caution.
Key Differences & Features
  • Constructors (__init__): Abstract classes often use them to initialize shared data attributes. Interfaces typically do not have them.
  • Private Variables: Starting a variable with __ (like __serial) makes it private to the base class using name mangling, preventing direct access from subclasses.
  • Decorators:
    • @abstractmethod must be the innermost decorator when combined with others (e.g., @classmethod @abstractmethod).
    • @property can be used with @abstractmethod to enforce that subclasses define specific attributes.
  • Multiple Inheritance: A single class can implement multiple interfaces (ABCs with only abstract methods) to achieve modular design.

Comments