An Abstract Base Class (ABC) in Python is a class that cannot be instantiated directly and is designed to be inherited by other classes. It allows you to define common methods and properties that must be implemented by any subclass. The main purpose of an abstract class is to provide a blueprint for other classes.
Why Use Abstract Base Classes (ABC)?
Enforce Method Implementation: Abstract classes ensure that subclasses implement specific methods. This is useful in large systems to maintain consistent interfaces.
Define a Common Interface: They help define a common interface that all subclasses must adhere to.
Prevent Instantiation of Abstract Classes: You cannot create an instance of an abstract class directly, preventing it from being used as a regular class.
How to Create Abstract Base Class?
To create an abstract class in Python, you need to:
Import ABC and abstractmethod from the abc module.
Use ABC as the base class.
Mark methods that must be implemented by subclasses with the @abstractmethod decorator.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
@abstractmethod
def move(self):
pass
class Dog(Animal):
def sound(self):
return "Woof"
def move(self):
return "Dog is running"
class Bird(Animal):
def sound(self):
return "Chirp"
def move(self):
return "Bird is flying"
# Trying to create an instance of the abstract class will raise an error
# animal = Animal() # This will raise TypeError
# Creating instances of subclasses
dog = Dog()
bird = Bird()
print(dog.sound()) # Output: Woof
print(dog.move()) # Output: Dog is running
print(bird.sound()) # Output: Chirp
print(bird.move()) # Output: Bird is flying
Explanation:
Animal Class is an abstract class that defines two abstract methods: sound() and move().
These methods do not have any implementation, and subclasses are required to provide an implementation for them.
Dog and Bird Classes inherit from Animal and implement the sound() and move() methods.
We cannot create an instance of the abstract Animal class directly, as it's not concrete. If we try, we’ll get a TypeError.
We can create instances of Dog and Bird, and since they implement all the abstract methods, they are concrete classes.
Abstract Methods:
An abstract method is a method that is declared in an abstract class but has no implementation. It is meant to be overridden in subclasses. The @abstractmethod decorator marks a method as abstract.
Abstract Base Class with Properties:
You can also have abstract properties in abstract base classes using @property and @abstractmethod.
from abc import ABC, abstractmethod
class Shape(ABC):
@property
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return 3.14 * (self.radius ** 2)
class Square(Shape):
def __init__(self, side):
self.side = side
@property
def area(self):
return self.side * self.side
# Creating instances
circle = Circle(5)
square = Square(4)
print(circle.area) # Output: 78.5
print(square.area) # Output: 16
Explanation:
Shape Class is an abstract base class with an abstract property area.
Circle and Square Classes inherit from Shape and implement the area property.
This ensures that any subclass of Shape will have to provide an implementation of the area property.
Abstract Class with Multiple Inheritance:
You can also use abstract base classes with multiple inheritance. For example, an abstract base class can be inherited by multiple subclasses, each implementing its own version of the abstract methods.
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
return "Car is starting"
def stop(self):
return "Car is stopping"
class Bike(Vehicle):
def start(self):
return "Bike is starting"
def stop(self):
return "Bike is stopping"
# Creating instances
car = Car()
bike = Bike()
print(car.start()) # Output: Car is starting
print(bike.start()) # Output: Bike is starting
Explanation:
Vehicle Class is an abstract class with two abstract methods: start() and stop().
Car and Bike Classes inherit from Vehicle and provide their own implementations of start() and stop() methods.
Benefits of Abstract Base Classes:
Enforces a Consistent Interface: By defining abstract methods in an abstract class, you ensure that all subclasses implement these methods, providing a consistent interface.
Code Organization: Abstract base classes help in organizing code by allowing you to define common functionality while still enforcing specific behavior for subclasses.
Preventing Direct Instantiation: Abstract classes cannot be instantiated, so they prevent creating objects that are not fully defined.
Conclusion:
Abstract Base Classes (ABC) in Python help enforce that certain methods must be implemented by subclasses, providing a structure to your program.
They are created using the ABC class and @abstractmethod decorator.
Abstract classes cannot be instantiated directly but can be inherited by concrete subclasses that implement the abstract methods.
Let me know if you need further clarification! 😊
0 Comments