gpt4 book ai didi

python - 普通类中的抽象方法

转载 作者:太空狗 更新时间:2023-10-30 01:04:50 25 4
gpt4 key购买 nike

我正在阅读官方 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()

不覆盖上面定义的抽象方法。

所以,这基本上是否意味着如果我的基类的 metaclass 不是 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 完成所有实际工作。 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

关于python - 普通类中的抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com