Using Abstract Classes
An abstract class is like a blueprint for other classes. It doesn’t do the work itself, but it lays out a plan for what other classes (called child classes) should do. Think of it like this:
- Imagine you’re designing different types of vehicles (like cars, bikes, and trucks).
- You know every vehicle needs to move, but how they move (driving, cycling, etc.) depends on the type of vehicle.
- An abstract class for "Vehicle" can declare the idea of a "move" method, but it leaves the actual details to the specific classes like "Car" or "Bike."
Why do we use abstract lasses?
- Enforce rules: Abstract classes make sure that every child class must follow the rules defined in the abstract class (like implementing certain methods).
- Organize code: They help structure your code so that it’s clear what all child classes should do.
- Focus on design: You define what should be done, but not how it should be done.
How do abstract classes work in Python?
In Python, you use the abc
module (short for Abstract Base Class) to create abstract classes. Abstract methods are defined using the @abstractmethod
Step 1: Create the abstract class
from abc import ABC, abstractmethod
class Vehicle(ABC): # ABC stands for Abstract Base Class
@abstractmethod
def move(self):
pass # No implementation here, just a placeholder
is now an abstract class.Vehicle - The
method is abstract, which means it must be implemented by any class that inherits frommove
.Vehicle
Step 2: Create child classes
Now, we create classes that inherit from Vehicle
move
class Car(Vehicle):
def move(self):
print("The car drives on roads.")
class Boat(Vehicle):
def move(self):
print("The boat sails on water.")
- Both
Car
andBoat
implement themove
method, each in their own way.
Step 3: Use the classes
car = Car()
car.move() # Output: The car drives on roads.
boat = Boat()
boat.move() # Output: The boat sails on water.
- You can now use
andCar
objects, and each knows how to perform theBoat
method.move
Key points to remember:
-
Can’t create objects from abstract classes: You can’t do
because an abstract class is incomplete. It’s just a blueprint.vehicle = Vehicle()
- Must implement abstract methods: Any class that inherits from an abstract class must provide its own version of the abstract methods.
- Abstract classes can have normal methods too: Abstract classes can include methods with code in them, which can be shared by all child classes.
Real-life analogy
Think of an abstract class like a contract:
- If you sign a contract (inherit an abstract class), you’re agreeing to fulfill certain conditions (implement abstract methods).
- The contract doesn’t tell you how to do it. It just says what needs to be done.
For example:
- An abstract class "Shape" might say every shape must have a method to calculate its area
.calculate_area()
- A rectangle and a circle can each calculate their area in their own way.