可正常工作:为什么classmethod的super需要第二个参数?
>>> 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
传递给函数是有意义的,因为它需要将基类类型绑定到该类的实际实例。但是classmethod不需要该类的特定实例。
编辑: 我得到的Python 3.2相同的错误,因为我在上面2.7 super(Bar).hello()
做。不过,我可以简单地做super().hello()
,这工作正常。
在python 3.x中它们修复了超级调用...在python2x中,它们只是没有认为它通过那么多(我的猜测是......)无论如何,我认为这将最终关闭如“为什么”的问题通常是... –
您可能会发现这个有用:http://stackoverflow.com/questions/11354786/super-confusing-python-multiple-inheritance-super?rq=1 – mdscruggs
@JoranBeasley咩,我已经问过几个为什么类型的问题还没有结束。 – jterrace