Bird
Raised Fist0
Pythonprogramming~20 mins

Abstract base classes overview in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
Abstract Base Class Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of abstract base class instantiation
What is the output of this Python code?
Python
from abc import ABC, abstractmethod

class Vehicle(ABC):
    @abstractmethod
    def start(self):
        pass

car = Vehicle()
AVehicle object created successfully
BTypeError: Can't instantiate abstract class Vehicle with abstract methods start
CNone
DAttributeError: 'Vehicle' object has no attribute 'start'
Attempts:
2 left
💡 Hint
Abstract base classes cannot be instantiated if they have abstract methods.
Predict Output
intermediate
2:00remaining
Output of subclass implementing abstract method
What is the output of this code?
Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side * self.side

sq = Square(4)
print(sq.area())
AAttributeError: 'Square' object has no attribute 'area'
BTypeError: Can't instantiate abstract class Square with abstract methods area
CNone
D16
Attempts:
2 left
💡 Hint
The subclass Square implements the abstract method area.
🧠 Conceptual
advanced
1:30remaining
Purpose of abstract base classes
Which option best describes the main purpose of abstract base classes in Python?
ATo provide a template for subclasses by enforcing implementation of certain methods
BTo allow creating instances of base classes with default behavior
CTo speed up program execution by precompiling methods
DTo automatically generate user interfaces for classes
Attempts:
2 left
💡 Hint
Think about why you would want to force subclasses to implement some methods.
Predict Output
advanced
2:00remaining
Output when abstract method is not implemented
What happens when you run this code?
Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    pass

d = Dog()
ATypeError: Can't instantiate abstract class Dog with abstract methods sound
BDog object created successfully
CAttributeError: 'Dog' object has no attribute 'sound'
DNone
Attempts:
2 left
💡 Hint
If a subclass does not implement all abstract methods, it cannot be instantiated.
🧠 Conceptual
expert
1:30remaining
Effect of @abstractmethod decorator
What is the effect of the @abstractmethod decorator in Python's abc module?
AIt automatically implements the method with default behavior
BIt makes the method private and inaccessible outside the class
CIt marks a method that must be overridden in any subclass before instantiation
DIt converts the method into a static method
Attempts:
2 left
💡 Hint
Consider what happens if a subclass does not provide its own version of the method.

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

  1. Step 1: Understand abstract base class role

    An abstract base class sets a template for other classes by defining methods that subclasses must implement.
  2. Step 2: Analyze options

    Only 'To define methods that must be implemented by subclasses' correctly states this purpose. The other options describe incorrect uses.
  3. Final Answer:

    To define methods that must be implemented by subclasses -> Option D
  4. 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

  1. Step 1: Recall abstract method syntax

    In Python, abstract methods are decorated with @abstractmethod from the abc module.
  2. 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.
  3. Final Answer:

    @abstractmethod\ndef method(self): pass -> Option A
  4. 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

  1. Step 1: Understand abstract base class behavior

    The abstract method sound must be implemented in subclass Dog. Here, Dog provides the implementation returning "Bark".
  2. 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.
  3. Final Answer:

    Bark -> Option A
  4. 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

  1. Step 1: Check abstract method implementation

    The abstract method move in Vehicle is decorated but has a body. However, Car does not implement move.
  2. Step 2: Understand instantiation rules

    Since Car lacks implementation of abstract method move, Python raises a TypeError when trying to create Car().
  3. Final Answer:

    TypeError: Can't instantiate abstract class Car with abstract method move -> Option B
  4. Quick Check:

    Missing abstract method implementation causes TypeError [OK]
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

  1. 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.
  2. Step 2: Verify subclass implementations

    Both Circle and Square implement area properly, allowing instantiation.
  3. 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.
  4. 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
  5. Quick Check:

    Use ABC and @abstractmethod for abstract base classes [OK]
Hint: Use ABC and @abstractmethod to enforce method implementation [OK]
Common Mistakes:
  • Not using @abstractmethod decorator
  • Not inheriting from ABC
  • Defining abstract methods without decorator