我正在阅读官方python documentation。
在上述链接中,第二行指出:
使用这个装饰器要求类的元类是ABCMeta或从中派生出来。
但是,我成功地能够定义下面给出的类。
from abc import abstractmethod
class A(object):
def __init__(self):
self.a = 5
@abstractmethod
def f(self):
return self.a
a = A()
a.f()
所以,上面的代码工作得很好。而且,我能够创建一个子类
class B(A):
def __init__(self):
super(B, self).__init__()
b = B()
b.f()
不覆盖上面定义的抽象方法。
所以,基本上这是否意味着如果我的基类的metaclass
不是ABCMeta
(或者从它派生),那么即使我有一个抽象方法,该类也不像抽象类一样?
那意味着,文档需要更清晰吗?
或者,这种行为在某种程度上是有用的,我错过了这一点。
所以,基本上这是否意味着如果我的基类的元类不是ABCMeta(或从它派生),那么即使我有一个抽象方法,该类也不像抽象类一样?
正确。
所有abstractmethod
都用__isabstractmethod__ = True
标记方法。 ABCMeta
完成所有实际工作。 Here是abstractmethod
的代码:
def abstractmethod(funcobj):
"""A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A
class that has a metaclass derived from ABCMeta cannot be
instantiated unless all of its abstract methods are overridden.
The abstract methods can be called using any of the normal
'super' call mechanisms.
Usage:
class C(metaclass=ABCMeta):
@abstractmethod
def my_abstract_method(self, ...):
...
"""
funcobj.__isabstractmethod__ = True
return funcobj