CodeBlanks Logo Icon CodeBlanks

ABC

Learn abstract classes with abc.ABC.

Abstract class (ABC)

An abstract class is a class that you do not instantiate directly and that acts as a template for subclasses. In Python you define it by inheriting from the ABC class in the abc module.

Example: from abc import ABC\nclass Animal(ABC):\n pass. Here Animal is now an abstract class. If you try to create an instance with Animal() you get a TypeError; but you can subclass it and instantiate the subclass. Abstract classes enforce a shared interface.

Inheriting from ABC

The shortest way to define an abstract class is to inherit from ABC. Even if you put no abstract methods in the body, ABC inheritance blocks any attempt to instantiate. This signals “this class should not be used alone”.

An abstract class gives subclasses a common behavior frame. A subclass inherits the abstract class and fills in the missing methods. So different subclasses conform to the same interface; the caller does not need to know which subclass it is.

Practice Define the abstract class

Start with from abc import ABC. Define an abstract class Animal(ABC); its body should be pass. Then print the abstract base relation with print(issubclass(Animal, ABC)).

Starter code

main.py
# Import ABC from abc and define the Animal abstract class

Sample solution

main.py
# Import ABC from abc and define the Animal abstract class
from abc import ABC

class Animal(ABC):
    pass

print(issubclass(Animal, ABC))

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens after defining Animal(ABC)?

  • Animal() returns a new instance
  • Animal() raises TypeError Correct answer
  • Animal automatically becomes a subclass
  • Animal is ignored

Explanation: An abstract class cannot be instantiated directly; it raises TypeError.

2 Complete the import line

Question
from ____ import ABC

class Animal(ABC):
    pass
Answer
from abc import ABC

class Animal(ABC):
    pass

Explanation: The abc module contains the ABC class.

3 Match the ABC parts

Term Meaning
abc Module
ABC Base class
class Animal(ABC) Abstract definition
TypeError Instantiation error

All lessons in Intermediate