这些是创建抽象基类并将其注册到具体类的不同方法:
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'>)
PS:请注意,只有#2也适用于Python 2