[英]Python 3.6: abc.abstracmethod on classmethod no check on class level call
With python 3.6, When I decorate an abstractmehod
with abc.abstractmethod
withing a class having metaclass=abc.ABCMeta
, the abstract method can be called from a class (not instance) point of view. 在python 3.6中,当我使用具有
metaclass=abc.ABCMeta
的类来用abc.abstractmethod
装饰abstractmehod
时,可以从类(而非实例)的角度调用abstract方法。
It seems that the abc
decorators are performing the checks when the class is instanciated, so it is not done when calling from instance. 实例化类时,似乎
abc
装饰器正在执行检查,因此从实例调用时未完成。
This behavior is highly disturbing and it looks like a bug in the abc
module. 此行为非常令人不安,它看起来像
abc
模块中的错误。
What did I miss? 我错过了什么?
Thanks 谢谢
Code example: 代码示例:
import abc
import sys
class P(metaclass=abc.ABCMeta):
@classmethod
@abc.abstractmethod
def acm(cls):
pass
class X(P):
pass
print("P.acm()", file=sys.stderr)
try:
P.acm()
print("OK")
except Exception as e:
print(f"KO: {e}")
print("P().acm()", file=sys.stderr)
try:
P().acm()
print("OK")
except Exception as e:
print(f"KO: {e}")
Results: 结果:
P.acm()
OK
P().acm()
KO: Can't instantiate abstract class P with abstract methods acm
This behavior is consistent with the behavior described in the documentation for @classmethod
. 此行为与
@classmethod
文档中描述的行为一致。
https://docs.python.org/3.6/library/functions.html?highlight=classmethod#classmethod https://docs.python.org/3.6/library/functions.html?highlight=classmethod#classmethod
"It can be called either on the class (such as Cf()) or on an instance (such as C().f())." “可以在类(例如Cf())或实例(例如C()。f())上调用它。”
In this case, it can't be called on an instance because it is abstract, but since it's a classmethod, it is still okay to call it on the class directly. 在这种情况下,无法在实例上调用它,因为它是抽象的,但是由于它是一种类方法,因此可以直接在类上调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.