Python:我为什么不能在类上使用“super”?

2024-04-25 11:53:17 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我不能使用super来获取类超类的方法?在

示例:

Python 3.1.3
>>> class A(object):
...     def my_method(self): pass
>>> class B(A):
...     def my_method(self): pass
>>> super(B).my_method
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    super(B).my_method
AttributeError: 'super' object has no attribute 'my_method'

(当然这是一个很小的例子,我可以做A.my_method,但是我需要这个来处理钻石继承的情况。)

根据super的文档,我想要的似乎应该是可能的。这是super的文档:(Emphasis mine)

super() -> same as super(__class__, <first argument>)

super(type) -> unbound super object

super(type, obj) -> bound super object; requires isinstance(obj, type)

super(type, type2) -> bound super object; requires issubclass(type2, type)

[non-relevant examples redacted]


Tags: 方法文档selfobjobjectmydeftype