编程语言
首页 > 编程语言> > python-普通类中的抽象方法

python-普通类中的抽象方法

作者:互联网

我正在阅读官方的python documentation.

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

Using this decorator requires that the class’s metaclass is ABCMeta or
is derived from it.

但是,我能够成功定义以下给定的类.

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

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

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

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

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

解决方法:

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

标签:abstract-methods,abstract-class,python
来源: https://codeday.me/bug/20191025/1927783.html