This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Polymorphism

Abstract decorator

face Josiah Wang

In our previous code, a problem is that a user can still create a new instance of the Device class via device = Device(). The NotImplementedError exception is only raised when device.turn_off() is invoked.

Perhaps a better way is to not allow instances of Device() to be created in the first place!

To do this, you explicitly turn Device into an abstract class, by subclassing from abc.ABC (Abstract Base Class).

You will also explicitly mark turn_off() as an abstract method using the @abstractmethod decorator. We will talk about decorators in more detail in a future lesson. There is no need to raise a NotImplementedError as before either. A simple pass statement is sufficient.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from abc import ABC, abstractmethod

class Device(ABC):
    def __init__(self, name):
        self.name = name

    @abstractmethod
    def turn_off(self):
        pass

device = Device("Some device")

If you run the code above, you will get a TypeError: Can't instantiate abstract class Device with abstract methods turn_off. The error message should be clear if you have understood everything correctly! You cannot create an instance of something that is abstract!

This is actually the recommended way to create an abstract class/method.