Python中

时间:2016-03-03 14:06:17

标签: python python-3.x interface metaclass method-resolution-order

这些是创建抽象基类并将其注册到具体类的不同方法:

进口:

from abc import ABCMeta
from abc import ABC
from abc import abstractmethod

方法1:

>>> 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'>)

方法2:

>>> 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'>)

方法3:

>>> 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'>)

方法4:

>>> 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'>)

方法5:

>>> 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'>)

的问题:

  1. 除了MRO之外,它们之间的区别是什么?
  2. 他们有不同的使用案例吗?
  3. 它们之间是否有首选或更多的pythonic方式?
  4. PS:请注意,只有#2也适用于Python 2

0 个答案:

没有答案