In python, we can use @abstractmethod to create a abstract class easily. In this tutorial, we will introduce how to use correctly.
Preliminary
In order to use @abstractmethod, we should import abc library. For example:
from abc import ABC, abstractmethod
How to create a abstract class using @abstractmethod?
Here is an example:
from abc import ABC, abstractmethod class Person(ABC): @abstractmethod def info(self): print("person info") @abstractmethod def name(self): pass
Python class Person is an abstract class, it contains two abstract functions: info() and name().
We should notice: we can not create an object using an abstract class. It means we can not create an instance using class Person.
For example:
p = Person()
We will see:
TypeError: Can’t instantiate abstract class Person with abstract methods info, name
How to use an abstract class correctly?
We can inherit an abstract class and overwrite all abstract functions.
For example:
class Tom(Person): def info(self): print("This is Tom") tom = Tom() tom.info()
Run this code, we will see:
TypeError: Can’t instantiate abstract class Tom with abstract methods name
Because there exists two abstract methods info() and name() in Person class. However, we only overwrite info() in Tom class.
We should overwrite all abstract methods in Person
For example:
class Tom(Person): def info(self): print("This is Tom") def name(self): print("this is tom name") tom = Tom() tom.info()
Run this code, we will see:
This is Tom