这些是创建抽象基类并将其注册到具体类的不同方法:
进口:
from abc import ABCMeta
from abc import ABC
from abc import abstractmethod
方法一:
>>> class A(metaclass=ABCMeta):
... @abstractmethod
... def hello(self):
... return
...
>>> class B(A):
... def hello(self):
... print("Hello World!")
...
>>> b = B()
>>> b.hello()
Hello World!
>>>
>>> print(B.__mro__)
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
方法二:
>>> class A(object):
... __metaclass__ = ABCMeta
...
... @abstractmethod
... def hello(self):
... return
...
>>> class B(A):
... def hello(self):
... print("Hello World!")
...
>>> b = B()
>>> b.hello()
Hello World!
>>>
>>> print(B.__mro__)
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
方法三:
>>> class A(ABC):
... @abstractmethod
... def hello(self):
... return
...
>>> class B(A):
... def hello(self):
... print("Hello World!")
...
>>> b = B()
>>> b.hello()
Hello World!
>>>
>>> print(B.__mro__)
(<class '__main__.B'>, <class '__main__.A'>, <class 'abc.ABC'>, <class 'object'>)
方法四:
>>> class A(metaclass=ABCMeta):
... @abstractmethod
... def hello(self):
... return
...
>>> class B(object):
... def hello(self):
... print("Hello World!")
...
>>> A.register(B)
<class '__main__.B'>
>>>
>>> b = B()
>>> b.hello()
Hello World!
>>>
>>> print(B.__mro__)
(<class '__main__.B'>, <class 'object'>)
方法五:
>>> class A(ABC):
... @abstractmethod
... def hello(self):
... return
...
>>> class B(object):
... def hello(self):
... print("Hello World!")
...
>>> A.register(B)
<class '__main__.B'>
>>>
>>> b = B()
>>> b.hello()
Hello World!
>>>
>>> print(B.__mro__)
(<class '__main__.B'>, <class 'object'>)
问题:
- 除了MRO,它们之间有什么区别?
- 他们有不同的用例吗?
- 在他们之间是否有一种首选或更 Pythonic 的方式来做到这一点?
PS:请注意,只有 #2 也适用于 Python 2