【问题标题】:python - abstract method in normal classpython - 普通类中的抽象方法
【发布时间】:2018-03-01 14:17:37
【问题描述】:

我正在阅读官方pythondocumentation

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

使用这个装饰器需要类的元类是 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(或从它派生),即使我有一个抽象方法,该类的行为也不像抽象类?

也就是说,文档需要更加清晰?

或者,这种行为是否有用,我没有抓住重点。

【问题讨论】:

  • 您期望它如何工作?我认为文档很清楚。另外,我想说,这里不是讨论文档问题的地方。
  • 我希望 Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it. 被强制执行?
  • @harman786 问题是 Python 中强制执行此类操作的唯一方法是使用元类。这是 Catch-22。

标签: python abstract-class abstract-methods


【解决方案1】:

所以,基本上这是否意味着如果我的基类的元类不是 ABCMeta(或派生自它),该类的行为不像 抽象类,即使我有一个抽象方法?

正确。

abstractmethod 所做的只是用__isabstractmethod__ = True 标记方法。 ABCMeta 完成所有实际工作。 Hereabstractmethod 的代码:

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

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 2016-11-24
    • 2021-10-18
    • 2012-09-16
    • 2011-02-17
    • 2012-09-21
    • 2010-10-30
    • 2016-07-05
    • 1970-01-01
    相关资源
    最近更新 更多