如何使用' super(type)'在Python中?AttributeError:' super'对象没有属性' test'

时间:2017-06-12 07:35:10

标签: python

这是我的代码:

class A(object):
   def test(self): pass
class B(A): pass

我的问题是,当我运行super(B).test时,我得到以下异常:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'super' object has no attribute 'test'

我看到了python文档:&#34; super(type) - &gt;未绑定的超级对象&#34;,为什么它没有工作?我希望有人可以举例说明使用&#34; super(type)&#34;对,谢谢

2 个答案:

答案 0 :(得分:2)

如果你想调用test,你不需要在这里使用super。

b = B()
b.test()

python中的关键字super通常用在内部类中。 感谢@PM 2Ring的提示。

答案 1 :(得分:1)

这真的很奇怪,正如zebo所说,这里没有必要使用super,在test的实例上调用B会调用从test继承的A方法。演示:

class A(object):
   def test(self):
       print('In test', self)

class B(A): pass

b = B()
b.test()

<强>输出

In test <__main__.B object at 0xb715fb6c>

但是, 可以使用super,如果您传递B的实例:

super(B, b).test()

super(B, B()).test()

这两行都提供与前一代码相同的输出。这一切都适用于Python 2&amp; 3.(当然,您需要在Python 2中执行from __future__ import print_function才能访问print函数。)

相关问题