Introduction π
An **Abstract Base Class (ABC)** in Python is a class that cannot be instantiated and is used to define a **blueprint** for other classes. ABCs ensure that child classes implement certain required methods. This is essential for building **structured, maintainable, and scalable** applications.
Note
π‘ They contain one or more abstract methods
π‘ Child classes must implement these abstract methods
1. Importing the ABC Tools π§±
import_abc.py
from abc import ABC, abstractmethodβ ABC β Base class to define an abstract class
β @abstractmethod β Marks methods that must be overridden
2. Creating a Simple Abstract Base Class π¨
simple_abc.py
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
# a = Animal() # β Error: Can't instantiate abstract classβ ABC cannot be instantiated
β Abstract method must be implemented in child class
3. Implementing Abstract Methods in Child Classes πΎ
child_implement.py
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
d = Dog()
print(d.sound())β Every subclass must implement sound()
β Failure β TypeError at runtime
4. Abstract Base Class with Constructor π
abc_constructor.py
from abc import ABC, abstractmethod
class Shape(ABC):
def __init__(self, color):
self.color = color
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side, color):
super().__init__(color)
self.side = side
def area(self):
return self.side * self.side
s = Square(5, "blue")
print(s.area())β ABCs can have regular methods and constructors
β Child classes must call parent constructor using super()
5. ABC with Multiple Abstract Methods π
multiple_methods.py
class Vehicle(ABC):
@abstractmethod
def start(self): pass
@abstractmethod
def stop(self): pass
class Car(Vehicle):
def start(self):
print("Car starting")
def stop(self):
print("Car stopping")
c = Car()
c.start()
c.stop()β All abstract methods must be implemented
6. Partially Abstract Classes (Concrete + Abstract) β‘
partial_abstract_class.py
class Device(ABC):
def info(self):
print("Device info")
@abstractmethod
def run(self):
pass
class Laptop(Device):
def run(self):
print("Laptop running")
l = Laptop()
l.info()
l.run()β ABCs can contain both abstract and non-abstract methods
β Useful for shared logic across subclasses
7. Real-World Example β Payment System π³
payment_abc.py
class Payment(ABC):
@abstractmethod
def pay(self, amount): pass
class Cash(Payment):
def pay(self, amount):
print(f"Paid {amount} in cash")
class Card(Payment):
def pay(self, amount):
print(f"Paid {amount} using card")
p = Card()
p.pay(500)8. Abstract Properties & Abstract Class Methods π§
abstract_property.py
class Product(ABC):
@property
@abstractmethod
def price(self):
pass
class Item(Product):
@property
def price(self):
return 500
i = Item()
print(i.price)β Even properties can be abstract and must be overridden
9. Abstract Class with Static Method π§©
abstract_staticmethod.py
class Tool(ABC):
@staticmethod
@abstractmethod
def info():
pass
class Hammer(Tool):
@staticmethod
def info():
return "Hammer tool"
print(Hammer.info())β Abstract static methods must also be implemented
10. Why Use Abstract Base Classes? π―
- β Enforces consistency across subclasses
- β Defines a common interface for all child classes
- β Organizes code into clear structures
- β Prevents incomplete implementations
- β Promotes clean, scalable system architecture
11. ABC vs Interface (in other languages) βοΈ
| Abstract Base Class | Interface (Java/C#) |
|---|---|
| Can have constructors | Cannot have constructors |
| Can have concrete methods | Only method signatures |
| Supports attributes | No attributes |
| Used via abc module | Built-in language feature |
12. Best Practices π‘
- β Use ABCs when multiple subclasses share a required structure
- β Keep abstract methods descriptive
- β Avoid adding unnecessary abstract methods
- β Use regular methods inside ABC for shared code
- β Use ABCs to define clean interfaces in large applications
Conclusion π
You now fully understand Abstract Base Classes in Python! Want the next topic? Try Interfaces, Magic Methods, Abstract Properties, or MRO. Just tell me! π