Python
@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.
Exercise 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()).
Show example solution
# 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())
Test yourself
-
Complete the import line
from abc import ABC, ____
class Animal(ABC):
@abstractmethod
def sound(self):
pass
Show answer
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
-
What happens if the subclass does not implement the abstract method?
- It acts like an abstract class, cannot be instantiated
- The abstract method is ignored
- The parent's body runs
- The program crashes
Show answer
It acts like an abstract class, cannot be instantiated — Missing abstract methods block instantiation.
-
Match the abstract method parts
- @abstractmethod
- Decorator
- def sound(self)
- Abstract signature
- class Dog(Animal)
- Subclass
- return "Woof"
- Implemented body
Next lesson: Abstract property