Python Abstract
Understanding Abstract Classes
An abstract class is like a blueprint or concept. It defines what should exist in a class (methods or properties) but does not provide complete implementation. You cannot create objects directly from an abstract class. The purpose is to enforce rules for subclasses, ensuring they implement essential methods.
Analogy: Imagine designing vehicles like Car, Boat, and Plane. You know all vehicles can move(), but each moves differently. You create a blueprint called Vehicle with an abstract move() method. Every subclass must implement it, ensuring consistency while allowing flexibility.
Python Example
from abc import ABC, abstractmethod
# Abstract class (blueprint)
class Person(ABC):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@abstractmethod
def display_name(self):
pass
# Subclass that implements the abstract method
class Student(Person):
def display_name(self):
print(f"Student: {self.first_name} {self.last_name}")
# Using the subclass
s = Student("Alice", "Smith")
s.display_name() # Output: Student: Alice Smith
Step-by-Step Explanation
- Abstract Class (Person): Inherits from
ABCand contains an abstract methoddisplay_name(). Cannot create objects directly. - Concrete Subclass (Student): Inherits from
Personand implementsdisplay_name(). Now objects can be created and used. - Why useful: Forces all subclasses to implement essential methods, provides a template, ensures consistency across subclasses.
Concrete Class vs Abstract Class
| Feature | Abstract Class | Concrete Class |
|---|---|---|
| Can you create an object? | No | Yes |
| Can it have abstract methods? | Yes | No |
| Purpose | Provide blueprint / enforce rules | Full implementation / ready to use |
| Example | Person with abstract display_name() | Student with implemented display_name() |
Analogy for Beginners
- Abstract class: Blueprint of a house. Cannot live in it, shows what rooms must exist.
- Concrete class: Actual house built from blueprint. Fully usable.
Summary
- Abstract classes define what should be done, not how.
- Subclasses must implement all abstract methods.
- Concrete classes can be instantiated and used.
- Abstract classes help enforce consistency and design rules in large programs.