Abstract base classes help us create a simple plan for other classes to follow. They make sure certain methods are always there.
Abstract base classes overview in Python
Start learning this pattern below
Jump into concepts and practice - no test required
from abc import ABC, abstractmethod class MyBaseClass(ABC): @abstractmethod def my_method(self): pass
Use ABC as the base class to create an abstract base class.
Use @abstractmethod to mark methods that must be defined in child classes.
Animal requires all animals to have a sound method.from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): pass
Vehicle is abstract and Car implements the required method.from abc import ABC, abstractmethod class Vehicle(ABC): @abstractmethod def start_engine(self): pass class Car(Vehicle): def start_engine(self): print("Car engine started")
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass # Trying to create Shape directly will cause an error # shape = Shape() # This will raise TypeError
This program shows an abstract class Animal with an abstract method sound. The classes Dog and Cat implement this method. Trying to create an Animal directly will cause an error.
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): pass class Dog(Animal): def sound(self): print("Woof!") class Cat(Animal): def sound(self): print("Meow!") # Uncommenting the next line will cause an error because Animal is abstract # animal = Animal() print("Creating Dog and Cat objects and calling their sound method:") dog = Dog() dog.sound() cat = Cat() cat.sound()
Time complexity: Abstract base classes do not affect runtime speed significantly; they are a design tool.
Space complexity: No extra memory cost beyond normal class usage.
Common mistake: Forgetting to implement all abstract methods in child classes causes errors.
Use abstract base classes when you want to enforce a common interface for many classes.
Abstract base classes define a template with methods that must be implemented.
They prevent creating objects from incomplete classes.
They help organize code and catch errors early.
Practice
abstract base class in Python?Solution
Step 1: Understand abstract base class role
An abstract base class sets a template for other classes by defining methods that subclasses must implement.Step 2: Analyze options
Only 'To define methods that must be implemented by subclasses' correctly states this purpose. The other options describe incorrect uses.Final Answer:
To define methods that must be implemented by subclasses -> Option DQuick Check:
Abstract base class = method template [OK]
- Thinking abstract classes can be instantiated
- Confusing abstract classes with regular classes
- Believing abstract classes store data only
Solution
Step 1: Recall abstract method syntax
In Python, abstract methods are decorated with@abstractmethodfrom theabcmodule.Step 2: Match options with correct syntax
Only '@abstractmethod\ndef method(self): pass' uses@abstractmethoddecorator correctly. 'def method(self): pass' misses the decorator, '@abstract\ndef method(self): pass' uses a wrong decorator name, and 'def abstract method(self): pass' uses invalid syntax.Final Answer:
@abstractmethod\ndef method(self): pass -> Option AQuick Check:
Use @abstractmethod decorator [OK]
- Omitting the @abstractmethod decorator
- Using wrong decorator names
- Writing invalid method definitions
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
print(Dog().sound())Solution
Step 1: Understand abstract base class behavior
The abstract methodsoundmust be implemented in subclassDog. Here,Dogprovides the implementation returning "Bark".Step 2: Predict output of print statement
CreatingDog()instance is allowed because all abstract methods are implemented. Callingsound()returns "Bark" which is printed.Final Answer:
Bark -> Option AQuick Check:
Implemented abstract method returns 'Bark' [OK]
- Expecting error despite full implementation
- Confusing abstract method with normal method
- Thinking abstract base class can be instantiated
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def move(self):
print("Moving")
class Car(Vehicle):
pass
car = Car()Solution
Step 1: Check abstract method implementation
The abstract methodmoveinVehicleis decorated but has a body. However,Cardoes not implementmove.Step 2: Understand instantiation rules
SinceCarlacks implementation of abstract methodmove, Python raises aTypeErrorwhen trying to createCar().Final Answer:
TypeError: Can't instantiate abstract class Car with abstract method move -> Option BQuick Check:
Missing abstract method implementation causes TypeError [OK]
- Assuming abstract methods with body are implemented
- Trying to instantiate subclass without method override
- Confusing SyntaxError with TypeError here
Shape with an abstract method area. Then, create two subclasses Circle and Square that implement area. Which code correctly achieves this?Solution
Step 1: Check abstract base class definition
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def __init__(self, r): self.r = r def area(self): return 3.14 * self.r ** 2 class Square(Shape): def __init__(self, s): self.s = s def area(self): return self.s * self.s correctly importsABCandabstractmethod, definesShapeas abstract with@abstractmethodonarea.Step 2: Verify subclass implementations
BothCircleandSquareimplementareaproperly, allowing instantiation.Step 3: Analyze other options
The other options miss the@abstractmethoddecorator or do not inherit fromABCproperly, so they are not true abstract base classes.Final Answer:
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def __init__(self, r): self.r = r def area(self): return 3.14 * self.r ** 2 class Square(Shape): def __init__(self, s): self.s = s def area(self): return self.s * self.s -> Option CQuick Check:
Use ABC and @abstractmethod for abstract base classes [OK]
- Not using @abstractmethod decorator
- Not inheriting from ABC
- Defining abstract methods without decorator
