The abstract class is the class that has only method lists.
The abstract class can't make an instance.
The inherited class must implement all abstract methods.
Import a Module
from abc import ABCMeta
ABCMeta (Abstract Base Class) forces a derived class to implement a specific method of the base class.
Abstract Class Declaration
class AbstractClass(metaclass=ABCMeta):
pass
You can declare the abstract class through the above way.
Let's declare the abstract class with some methods.
from abc import ABCMeta, abstractmethod
class AbstractClass(metaclass=ABCMeta):
@abstractmethod
def abstract_method1(self):
pass
@abstractmethod
def abstract_method2(self):
pass
Let's try to create an instance.
obj = AbstractClass()
# Traceback (most recent call last):
# File "main.py", line 17, in <module>
# obj = AbstractClass()
# TypeError: Can't instantiate abstract class AbstractClass with abstract methods abstract_method1, abstract_method2
As I said, the abstract class can't make an instance.
Abstract Class Inheritance
Create a child class inherited from the abstract class.
class ChildClass(AbstractClass):
def abstract_method1(self):
print("abstract method 1")
obj = ChildClass()
# Traceback (most recent call last):
# File "main.py", line 23, in <module>
# obj = ChildClass()
# TypeError: Can't instantiate abstract class ChildClass with abstract methods abstract_method2
As I also said, the inherited class has to implement all abstract methods.
This is the full source code for the abstract class example.
from abc import ABCMeta, abstractmethod
class AbstractClass(metaclass=ABCMeta):
@abstractmethod
def abstract_method1(self):
pass
@abstractmethod
def abstract_method2(self):
pass
class ChildClass(AbstractClass):
def abstract_method1(self):
print("abstract method 1")
def abstract_method2(self):
print("abstract method 2")
obj = ChildClass()
obj.abstract_method1()
obj.abstract_method2()
# abstract method 1
# abstract method 2
'Python' 카테고리의 다른 글
[Python] Beautiful Soup4 module (0) | 2020.10.09 |
---|---|
[Python] requests module (0) | 2020.10.08 |
[Python] pip (0) | 2020.09.11 |
[Python] venv (0) | 2020.08.29 |
[Python] pyenv (0) | 2020.08.29 |
댓글