CodeBlanks Logo Icon CodeBlanks

@abstractmethod

Learn abstract methods with @abstractmethod.

@abstractmethod

The @abstractmethod decorator marks a method as “the subclass must fill this in”. abstractmethod is imported from the abc module.

Example: class Animal(ABC):\n @abstractmethod\n def sound(self):\n pass. Here sound is left empty but the subclass must fill it. If a subclass is instantiated without writing sound, a TypeError is raised. So the abstract class enforces behavior.

The subclass fills it in

An abstract method is redefined in the subclass with the same signature. If the subclass does not write the method, Python refuses to instantiate. This prevents the subclass from forgetting the behavior.

Example: class Dog(Animal):\n def sound(self):\n return "Woof". Since Dog now implements sound, it can be instantiated; Dog().sound() returns "Woof". If you skip sound, Dog() also raises TypeError.

Practice Dog class implements sound

Start with from abc import ABC, abstractmethod. Define the abstract class Animal(ABC); inside, use @abstractmethod with def sound(self): and pass. Then define class Dog(Animal):; in the body write def sound(self): and return "Woof". Finally create d = Dog() and print with print(d.sound()).

Starter code

main.py
# Import ABC and abstractmethod from abc, write Animal and Dog classes

Sample solution

main.py
# Import ABC and abstractmethod from abc, write Animal and Dog classes
from abc import ABC, abstractmethod

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

class Dog(Animal):
    def sound(self):
        return "Woof"

d = Dog()
print(d.sound())

Expected output

Woof

Questions and answers

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

1 Complete the import line

Question
from abc import ABC, ____

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass
Answer
from abc import ABC, abstractmethod

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

Explanation: abstractmethod is imported from the abc module.

2 What happens if the subclass does not implement the abstract method?

  • It acts like an abstract class, cannot be instantiated Correct answer
  • The abstract method is ignored
  • The parent's body runs
  • The program crashes

Explanation: Missing abstract methods block instantiation.

3 Match the abstract method parts

Term Meaning
@abstractmethod Decorator
def sound(self) Abstract signature
class Dog(Animal) Subclass
return "Woof" Implemented body

All lessons in Intermediate