python - 正常的抽象方法 class
python - abstract method in normal class
我正在看官方pythondocumentation.
在提到的link中,第二行指出:
Using this decorator requires that the class’s metaclass is ABCMeta or
is derived from it.
但是,我成功地定义了下面给定的 class。
from abc import abstractmethod
class A(object):
def __init__(self):
self.a = 5
@abstractmethod
def f(self):
return self.a
a = A()
a.f()
所以,上面的代码运行良好。
而且,我能够创建一个 subclass
class B(A):
def __init__(self):
super(B, self).__init__()
b = B()
b.f()
没有覆盖上面定义的抽象方法。
所以,基本上这是否意味着如果我的基础 class 的 metaclass
不是 ABCMeta
(或派生自它),则 class 不会表现像一个抽象 class 即使我有一个抽象方法在里面?
也就是说,文档需要更加清晰?
或者,这种行为是否有用,我没抓住重点。
So, basically does this mean that if my base class's metaclass is not
ABCMeta(or derived from it), the class does not behave like an
abstract class even though I have an abstract method in it?
正确。
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
我正在看官方pythondocumentation.
在提到的link中,第二行指出:
Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it.
但是,我成功地定义了下面给定的 class。
from abc import abstractmethod
class A(object):
def __init__(self):
self.a = 5
@abstractmethod
def f(self):
return self.a
a = A()
a.f()
所以,上面的代码运行良好。 而且,我能够创建一个 subclass
class B(A):
def __init__(self):
super(B, self).__init__()
b = B()
b.f()
没有覆盖上面定义的抽象方法。
所以,基本上这是否意味着如果我的基础 class 的 metaclass
不是 ABCMeta
(或派生自它),则 class 不会表现像一个抽象 class 即使我有一个抽象方法在里面?
也就是说,文档需要更加清晰?
或者,这种行为是否有用,我没抓住重点。
So, basically does this mean that if my base class's metaclass is not ABCMeta(or derived from it), the class does not behave like an abstract class even though I have an abstract method in it?
正确。
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