【问题标题】:Python: Why can't I use `super` on a class?Python:为什么我不能在类上使用`super`?
【发布时间】:2011-06-08 20:17:17
【问题描述】:

为什么我不能使用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__, <first argument>)

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

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

super(type, type2) -> 绑定超级 目的;需要 issubclass(type2, 类型)

[编辑不相关的例子]

【问题讨论】:

  • 我删除了我的答案 - 我得到了同样的错误。很奇怪,会再研究一下。

标签: python class python-3.x super


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

根据this 看来我只需要打电话给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

【讨论】:

  • 很高兴链接源提供帮助。 :)
  • 记住这会给你未绑定的方法;您通常需要说super(B, self) 的原因是为了获取绑定到对象的超级对象,以检索绑定的方法。
  • ...这对我来说看起来很奇怪,但在 Python 2.7 中完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2010-09-05
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多