Python provides the abc (Abstract Base Class) module to create and work with abstract classes and methods.
What is Abstraction?
Abstraction means hiding complex implementation details and exposing only essential features. It allows you to define a standard interface that multiple classes can implement in different ways.Example: When you use a car, you only interact with methods like start() or accelerate() — you don't worry about how the engine internally works.
In programming, abstraction helps achieve this clean separation between interface and implementation.
What are Abstract Classes?
An abstract class in Python is a class that cannot be instantiated directly. It may contain one or more abstract methods — methods declared but not implemented. Subclasses that inherit from an abstract class must implement all abstract methods to become concrete (usable) classes.Creating an Abstract Class
Abstract classes are defined using the abc module. Example:from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
Here:
- Shape is an abstract class.
- It inherits from ABC (Abstract Base Class).
- @abstractmethod decorator marks methods that must be implemented by child classes.
Trying to create an object of Shape will cause an error:
s = Shape() # TypeError
Output:
TypeError: Can't instantiate abstract class Shape without an implementation for abstract methods 'area', 'perimeter'
Implementing Abstract Methods in Subclasses
To use an abstract class, you must create a subclass that provides concrete implementations of all abstract methods.class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
def perimeter(self):
return 2 * 3.14 * self.radius
c = Circle(5)
print("Area:", c.area())
print("Perimeter:", c.perimeter())
Output:
Area: 78.5
Perimeter: 31.400000000000002
Here, Circle implements all abstract methods, so it can now be instantiated normally.
Abstract Class with Concrete Methods
An abstract class can also contain concrete methods — regular methods with implementations. These provide shared functionality for all subclasses.Example:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
def fuel_type(self):
print("Diesel or Petrol")
class Car(Vehicle):
def start(self):
print("Car started with a key")
my_car = Car()
my_car.start()
my_car.fuel_type()
Output:
Car started with a key
Diesel or Petrol
Here, subclasses must implement start(), but they can reuse fuel_type() as it is.
Abstract Properties
You can also define abstract properties using the @property decorator along with @abstractmethod.from abc import ABC, abstractmethod
class Device(ABC):
@property
@abstractmethod
def brand(self):
pass
class Phone(Device):
@property
def brand(self):
return "Samsung"
p = Phone()
print(p.brand)
Output:
Samsung
Here, brand is an abstract property that must be implemented in the subclass.
The @property decorator transforms a method into a getter, enabling access to its return value as if it were a direct attribute. For example, p.brand instead of p.brand().
Interfaces in Python
Unlike Java or C++, Python doesn't have a separate interface keyword. Instead, you can create interfaces by defining an abstract class that contains only abstract methods — with no implementation details.Example:
from abc import ABC, abstractmethod
class PaymentGateway(ABC):
@abstractmethod
def pay(self, amount):
pass
class PayPal(PaymentGateway):
def pay(self, amount):
print(f"Paid {amount} via PayPal")
class Stripe(PaymentGateway):
def pay(self, amount):
print(f"Paid {amount} via Stripe")
paypal = PayPal()
stripe = Stripe()
paypal.pay(200)
stripe.pay(350)
Output:
Paid 200 via PayPal
Paid 350 via Stripe
Here:PaymentGateway acts as an interface.
PayPal and Stripe are concrete implementations of that interface.
Checking Subclass Relationships
Python provides two useful functions to check relationships between abstract classes and their subclasses:issubclass() → Checks if a class inherits from another.
isinstance() → Checks if an object is an instance of a given class.
Example:
class Shape:
def area(self):
raise NotImplementedError("Subclasses must implement this method")
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
print(issubclass(Rectangle, Shape)) # True
r = Rectangle(5, 10)
print(isinstance(r, Shape)) # True
Output:
True
True
Summary
Abstract classes and interfaces help you enforce structure and consistency across different parts of your code. They define what methods should exist in a class, leaving the details of how they are implemented to the subclasses.| Concept | Description |
|---|---|
| Abstraction | Hides internal details and shows only essential features |
| Abstract Class | A class that cannot be instantiated directly |
| ABC | Base class for defining abstract classes (from the abc module) |
| @abstractmethod | Decorator for defining abstract methods |
| Interface | Abstract class containing only abstract methods |
| Concrete Method | Normal method defined inside an abstract class |
| issubclass() / isinstance() | Used to verify inheritance relationships |