【发布时间】:2013-07-08 15:28:05
【问题描述】:
这按预期工作:
>>> class Foo(object):
... @classmethod
... def hello(cls):
... print 'hello, foo'
...
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... super(Bar, cls).hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
hello, foo
我也可以显式调用基类:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... Foo.hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
hello, foo
我想知道为什么我不能省略super 的第一个参数,像这样:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print 'hello, bar'
... super(Bar).hello()
...
>>> b = Bar()
>>> b.hello()
hello, bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in hello
AttributeError: 'super' object has no attribute 'hello'
当没有第二个参数的super 调用的结果似乎是超类型中的类类型时:
>>> class Bar(Foo):
... @classmethod
... def hello(cls):
... print Foo, type(Foo)
... print super(Bar), type(super(Bar))
... print cls, type(cls)
...
>>> b = Bar()
>>> b.hello()
<class '__main__.Foo'> <type 'type'>
<super: <class 'Bar'>, NULL> <type 'super'>
<class '__main__.Bar'> <type 'type'>
我想我只是想知道这里的设计。为什么我需要将类对象传递给超级调用以获取对基类类型Foo 的引用?对于普通方法,将self 传递给函数是有意义的,因为它需要将基类类型绑定到类的实际实例。但是类方法不需要类的特定实例。
编辑:
我在 Python 3.2 中遇到与上面 2.7 中 super(Bar).hello() 相同的错误。但是,我可以简单地执行super().hello() 并且效果很好。
【问题讨论】:
-
在 python 3.x 中,他们修复了很多超级调用......在 python2x 中,他们只是没有考虑那么多(我的猜测......)无论如何我认为这将结束关闭为“为什么”问题通常是......
-
您可能会发现这很有用:stackoverflow.com/questions/11354786/…
-
@JoranBeasley meh,在此之前我已经问过几个为什么类型的问题还没有结束。
-
@JoranBeasley:对于许多这样的问题,当涉及到 Python 时,原因有据可查,使得这些问题可以完美回答。 Python 3 添加了一个隐式的
__class__范围变量,因此您可以省略参数,super()将检查调用框架以获取类型和绑定参数(self或cls)。 -
@jterrace:因为只有 没有 参数的版本才会在周围范围内查找要绑定的类型和对象。
标签: python python-3.x inheritance python-2.x class-method