Abstract Method
Abstract Method is a method that should be redefined in subclasses.
To create an abstract method, you should import the @abstractmethod
decorator from the abc
library.
pythonfrom abc import ABC, abstractmethod
Note
Pay attention: decorator is imported without the
@
symbol.
9
1
2
3
4
5
6
7
8
from abc import ABC, abstractmethod
class SomeClass(ABC):
@abstractmethod
def some_method():
pass
instance = SomeClass() # TypeError
12345678from abc import ABC, abstractmethod class SomeClass(ABC): @abstractmethod def some_method(): pass instance = SomeClass() # TypeError
The abstract methods should be implemented in subclasses. You can't create a subclass without redefining all abstract methods:
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from abc import ABC, abstractmethod
class AbstractParent(ABC):
@abstractmethod
def first_method():
pass
@abstractmethod
def second_method():
pass
class Child(AbstractParent):
def first_method(self):
print("The first method")
instance = Child() # TypeError
12345678910111213141516from abc import ABC, abstractmethod class AbstractParent(ABC): @abstractmethod def first_method(): pass @abstractmethod def second_method(): pass class Child(AbstractParent): def first_method(self): print("The first method") instance = Child() # TypeError
The class Child
saved the Abstract Class state because the second_method
is not redefined, and the ABC
class exists in the inheritance hierarchy.
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from abc import ABC, abstractmethod
class AbstractParent(ABC):
@abstractmethod
def first_method():
pass
@abstractmethod
def second_method():
pass
class Child(AbstractParent):
def first_method(self):
print("The first method")
def second_method(self):
print("The second method")
instance = Child()
instance.first_method()
instance.second_method()
12345678910111213141516171819202122from abc import ABC, abstractmethod class AbstractParent(ABC): @abstractmethod def first_method(): pass @abstractmethod def second_method(): pass class Child(AbstractParent): def first_method(self): print("The first method") def second_method(self): print("The second method") instance = Child() instance.first_method() instance.second_method()
Note
The abstract classes and methods exist to provide a strict class structure.
Tout était clair ?
Merci pour vos commentaires !
Section 4. Chapitre 6
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion