Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Abstract base classes overview
📖 Scenario: Imagine you are designing a simple system for different types of vehicles. Each vehicle must have a method to start the engine, but how it starts can be different for each vehicle type.
🎯 Goal: You will create an abstract base class called Vehicle with an abstract method start_engine. Then, you will create two classes, Car and Motorcycle, that inherit from Vehicle and implement the start_engine method differently. Finally, you will create instances of these classes and call their start_engine methods to see the output.
📋 What You'll Learn
Create an abstract base class called Vehicle using the abc module
Define an abstract method start_engine inside Vehicle
Create a class Car that inherits from Vehicle and implements start_engine with a print statement
Create a class Motorcycle that inherits from Vehicle and implements start_engine with a different print statement
Create instances of Car and Motorcycle and call their start_engine methods
Print the outputs of calling start_engine on both instances
💡 Why This Matters
🌍 Real World
Abstract base classes help define common interfaces for different types of objects, ensuring they all have certain methods. This is useful in designing systems where different objects share behavior but implement it differently.
💼 Career
Understanding abstract base classes is important for writing clean, maintainable code in many software development jobs, especially when working with frameworks or large codebases that rely on polymorphism.
Progress0 / 4 steps
1
Create the abstract base class
Import the ABC and abstractmethod from the abc module. Then create an abstract base class called Vehicle that inherits from ABC. Inside Vehicle, define an abstract method called start_engine using the @abstractmethod decorator.
Python
Hint
Use from abc import ABC, abstractmethod to import the tools for abstract classes. Then create class Vehicle(ABC):. Use @abstractmethod above start_engine to mark it as abstract.
2
Create the Car class
Create a class called Car that inherits from Vehicle. Inside Car, implement the start_engine method to print the exact text "Car engine started with a key.".
Python
Hint
Define class Car(Vehicle):. Inside it, write def start_engine(self): and use print("Car engine started with a key.").
3
Create the Motorcycle class
Create a class called Motorcycle that inherits from Vehicle. Inside Motorcycle, implement the start_engine method to print the exact text "Motorcycle engine started with a button.".
Python
Hint
Define class Motorcycle(Vehicle):. Inside it, write def start_engine(self): and use print("Motorcycle engine started with a button.").
4
Create instances and call start_engine
Create an instance called my_car of the Car class and an instance called my_motorcycle of the Motorcycle class. Then call the start_engine method on both instances. Print the outputs exactly as they appear.
Python
Hint
Create my_car = Car() and my_motorcycle = Motorcycle(). Then call my_car.start_engine() and my_motorcycle.start_engine().
Practice
(1/5)
1. What is the main purpose of an abstract base class in Python?
easy
A. To store data without any methods
B. To create objects directly from the base class
C. To automatically run code without subclassing
D. To define methods that must be implemented by subclasses
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 D
Quick Check:
Abstract base class = method template [OK]
Hint: Abstract base classes require method implementation [OK]
Common Mistakes:
Thinking abstract classes can be instantiated
Confusing abstract classes with regular classes
Believing abstract classes store data only
2. Which of the following is the correct way to declare an abstract method in a Python abstract base class?
easy
A. @abstractmethod\ndef method(self): pass
B. @abstract\ndef method(self): pass
C. def abstract method(self): pass
D. def method(self): pass
Solution
Step 1: Recall abstract method syntax
In Python, abstract methods are decorated with @abstractmethod from the abc module.
Step 2: Match options with correct syntax
Only '@abstractmethod\ndef method(self): pass' uses @abstractmethod decorator 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 A
Quick Check:
Use @abstractmethod decorator [OK]
Hint: Use @abstractmethod decorator for abstract methods [OK]
Common Mistakes:
Omitting the @abstractmethod decorator
Using wrong decorator names
Writing invalid method definitions
3. What will be the output of this code?
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
print(Dog().sound())
medium
A. Bark
B. TypeError
C. None
D. AttributeError
Solution
Step 1: Understand abstract base class behavior
The abstract method sound must be implemented in subclass Dog. Here, Dog provides the implementation returning "Bark".
Step 2: Predict output of print statement
Creating Dog() instance is allowed because all abstract methods are implemented. Calling sound() returns "Bark" which is printed.
Final Answer:
Bark -> Option A
Quick Check:
Implemented abstract method returns 'Bark' [OK]
Hint: Subclass must implement all abstract methods to instantiate [OK]
Common Mistakes:
Expecting error despite full implementation
Confusing abstract method with normal method
Thinking abstract base class can be instantiated
4. Identify the error in this code snippet:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def move(self):
print("Moving")
class Car(Vehicle):
pass
car = Car()
medium
A. No error, code runs fine
B. TypeError: Can't instantiate abstract class Car with abstract method move
C. SyntaxError due to missing method implementation
D. AttributeError: 'Car' object has no attribute 'move'
Solution
Step 1: Check abstract method implementation
The abstract method move in Vehicle is decorated but has a body. However, Car does not implement move.
Step 2: Understand instantiation rules
Since Car lacks implementation of abstract method move, Python raises a TypeError when trying to create Car().
Final Answer:
TypeError: Can't instantiate abstract class Car with abstract method move -> Option B
Hint: All abstract methods must be implemented before instantiation [OK]
Common Mistakes:
Assuming abstract methods with body are implemented
Trying to instantiate subclass without method override
Confusing SyntaxError with TypeError here
5. You want to create an abstract base class Shape with an abstract method area. Then, create two subclasses Circle and Square that implement area. Which code correctly achieves this?
hard
A. from abc import ABC
class Shape(ABC):
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * self.r ** 2
class Square(Shape):
def area(self):
return self.s * self.s
B. class Shape:
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * self.r ** 2
class Square(Shape):
def area(self):
return self.s * self.s
C. 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
D. from abc import ABC, abstractmethod
class Shape(ABC):
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * self.r ** 2
class Square(Shape):
def area(self):
return self.s * self.s
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 imports ABC and abstractmethod, defines Shape as abstract with @abstractmethod on area.
Step 2: Verify subclass implementations
Both Circle and Square implement area properly, allowing instantiation.
Step 3: Analyze other options
The other options miss the @abstractmethod decorator or do not inherit from ABC properly, 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 C
Quick Check:
Use ABC and @abstractmethod for abstract base classes [OK]
Hint: Use ABC and @abstractmethod to enforce method implementation [OK]