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

Ram*_*hum 7 python class super python-3.x

为什么我不能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'
Run Code Online (Sandbox Code Playgroud)

(当然,这是一个简单的案例,我可以做A.my_method,但我需要这个钻石继承案例.)

根据super文件,似乎我想要的应该是可能的.这是super文件:(强调我的)

super() - >相同 super(__class__, <first argument>)

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

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

super(type,type2) - >绑定超级对象; 需要issubclass(type2,type)

[编辑的非相关示例]

Jam*_*mes 8

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

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


Ram*_*hum 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
Run Code Online (Sandbox Code Playgroud)

  • 请记住,这将为您提供未绑定的方法; 你通常需要说'super(B,self)`的原因是为了获得一个绑定到一个对象的超级对象,以检索绑定的方法. (3认同)