how to use 'super(type)' in Python?AttributeError: 'super' object has no attribute 'test'

how to use 'super(type)' in Python?AttributeError: 'super' object has no attribute 'test'

这是我的代码:

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 文档:"super(type) -> unbound super object",为什么它不起作用?我希望有人能给出一个正确使用 "super(type)" 的例子,谢谢

如果要调用test,这里不需要用super

b = B()
b.test()

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

这真的很奇怪,正如 zebo 所说,这里不需要使用 super,在 B 的实例上调用 test 将调用 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 和 3。(当然你需要在 Python 2 中执行 from __future__ import print_function 才能访问 print 函数)。