python-普通类中的抽象方法

har*_*nds 5 python abstract-class abstract-methods

我正在阅读python官方文档

在提到的链接中,第二行指出:

使用此装饰器要求该类的元类为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()
Run Code Online (Sandbox Code Playgroud)

因此,上面的代码工作正常。而且,我能够创建一个子类

class B(A):
    def __init__(self):
        super(B, self).__init__() 

b = B()
b.f()
Run Code Online (Sandbox Code Playgroud)

在不覆盖上面定义的抽象方法的情况下。

因此,基本上,这是否意味着如果我的基类metaclass不是ABCMeta(或从其派生的),即使我具有抽象方法,该类的行为也不会像抽象类一样?

这意味着文档需要更清晰吗?

或者,这种行为在某种程度上有用吗?我错过了重点。

Col*_*lin 5

因此,基本上,这是否意味着如果我的基类的元类不是ABCMeta(或从其派生),即使我具有抽象方法,该类的行为也不像抽象类?

正确。

所有的abstractmethod操作都用标记方法__isabstractmethod__ = TrueABCMeta做所有真正的工作。是以下代码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
Run Code Online (Sandbox Code Playgroud)