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

7 投票
2 回答
545 浏览
提问于 2025-04-16 09:55

为什么我不能用 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 的说明:(我强调的部分)

super() -> 和 super(__class__, <第一个参数>) 是一样的

super(type) -> 未绑定的 super 对象

super(type, obj) -> 绑定的 super 对象;需要 isinstance(obj, type)

super(type, type2) -> 绑定的 super 对象;需要 type2type 的子类

[与主题无关的例子省略]

2 个回答

8

看起来你需要一个B的实例,作为第二个参数传入。

http://www.artima.com/weblogs/viewpost.jsp?thread=236275

6

根据这个链接,看起来我只需要调用 super(B, B).my_method

>>> super(B, B).my_method
<function my_method at 0x00D51738>
>>> super(B, B).my_method is A.my_method
True

撰写回答