Abstract Classes (Using abc module)
Abstract classes are classes that cannot be instantiated and are designed to be inherited by other
classes. They can have both abstract methods (methods without implementation) and concrete
methods (methods with implementation). In other words:
- Abstract classes are incomplete classes that other classes can inherit from. You can't create
an object directly from an abstract class, but you can use it as a base for other classes.
- An abstract class is like a blueprint for other classes. It defines some basic rules or
guidelines but doesn't give the full details.
It is used when you want all child classes to implement specific methods.
Example 1:
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
def concrete_method(self):
print("Concrete method")
class ConcreteClass(AbstractClass):
def abstract_method(self):
print("Implementing abstract method")
concrete = ConcreteClass()
concrete.abstract_method() # Output: Implementing abstract method
concrete.concrete_method() # Output: Concrete method
- ABC is a base class for abstract classes.
- @abstractmethod decorator is used to define abstract methods.
Example 2:
from abc import ABC, abstractmethod
class Shape(ABC): # Inherits from ABC (Abstract Base Class)
@abstractmethod
def area(self):
pass # No body here, just a rule
#Now a child class must implement area()
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
#Use it:
# shape = Shape() # Error: Can't instantiate abstract class
circle = Circle(5)
print(circle.area()) # Output: 78.5
Explanation:
Shape is an abstract class with an abstractmethod area().
Circle must implement area(), or Python raises an error.
Prevents incomplete class usage.
from abc import ABC, abstractmethod
# Abstract class
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * (self.radius ** 2)
# Create instances of Rectangle and Circle
rectangle = Rectangle(5, 3)
circle = Circle(4)
print(rectangle.area()) # Outputs: 15
print(circle.area()) # Outputs: 50.26548245743669
# Import required tools for abstract classes
# ABC = Abstract Base Class
from abc import ABC, abstractmethod
# Define abstract class Shape
# (ABC) makes this an abstract class
class Shape(ABC):
# @abstractmethod marks this as an abstract method
# Must be implemented by child classes
@abstractmethod
def area(self):
pass # pass means "do nothing" - just a placeholder
@abstractmethod
def perimeter(self):
pass
# Concrete class that implements Shape
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
# Must implement area() (required by Shape)
def area(self):
# Calculate and return area
return self.width * self.height
# Must implement perimeter() (required by Shape)
def perimeter(self):
# Calculate and return perimeter
return 2 * (self.width + self.height)
# This would fail because Shape is abstract:
# s = Shape()
# Create Rectangle object
r = Rectangle(5, 3)
# Call implemented methods
print(r.area()) # Output: 15 (5 * 3)
print(r.perimeter()) # Output: 16 (2*(5+3))
Interfaces in Python
Python does not have a built-in concept of interfaces like some other languages.
However, you can use abstract classes to achieve similar functionality
In Python, interfaces are created using abstract classes with all abstract methods/
only method definitions (def method_name(self)).
Example 1: Example: Interface-like Behavior Using ABC
from abc import ABC, abstractmethod
class Printable(ABC):
@abstractmethod
def print(self):
pass
class Document(Printable):
def print(self):
print("Printing a document")
Explanation:
class Printable(ABC): defines an abstract class "Printable" that acts as an interface.
class Document(Printable): defines a class "Document" that implements the
"Printable" interface.
Example 2:
from abc import ABC, abstractmethod
# Interface (all methods are abstract)
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount):
pass
# Implementing classes
class CreditCard(PaymentMethod):
def pay(self, amount):
print(f"Paying #{amount} with credit card")
class PayPal(PaymentMethod):
def pay(self, amount):
print(f"Paying #{amount} with PayPal")
# Using the interface
def process_payment(payment_method, amount):
payment_method.pay(amount)
card = CreditCard()
paypal = PayPal()
process_payment(card, 100) # Output: Paying #100 with credit card
process_payment(paypal, 50) # Output: Paying #50 with PayPal
Summary Table
Concept Meaning Keyword / Tool
Class Blueprint class
Object Real thing created from class obj = Class()
Constructor Initializes object __init__
Inheritance Child gets parent features class Child(Parent)
Polymorphism Same method name, different actions def same_method()
Abstract Class Rulebook, not for direct use from abc import ABC
Interface Like contract for methods Abstract class with only method declarations