πŸ›οΈ Python OOP β€” Abstract Base Class (ABC)

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

πŸ’‘ Abstract Base Classes are created using the abc module
πŸ’‘ 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 ClassInterface (Java/C#)
Can have constructorsCannot have constructors
Can have concrete methodsOnly method signatures
Supports attributesNo attributes
Used via abc moduleBuilt-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 πŸŽ‰

>>β€œAbstract Base Classes enforce structure and consistency β€” forming the backbone of clean, powerful object-oriented design.” ✨

You now fully understand Abstract Base Classes in Python! Want the next topic? Try Interfaces, Magic Methods, Abstract Properties, or MRO. Just tell me! 😊