【发布时间】:2012-09-25 13:08:39
【问题描述】:
可能重复:
Why do I have to specify my own class when using super(), and is there a way to get around it?
我正在阅读这本书 - "Core Python Programming",我真的觉得它非常好。但是我在研究继承主题时有一段时间感到困惑..
某处的书说-我们可以使用super() 调用super class method,这将为我们找到基类方法,而且我们不需要显式传递self,就像我们没有super..
下面是示例代码:-
# Invoking super class method without super() .. Need to pass `self` as argument
class Child(Parent):
def foo(self):
Parent.foo(self)
# Invoking with super().
# No need to pass `self` as argument to foo()
class Child(Parent1, Parent2):
def foo(self):
super(Child, self).foo()
print 'Hi, I am Child-foo()'
我的问题是 - 为什么我们必须将 classname 传递给 super() 调用.. 因为可以从调用 super 的类中推断出类名..
所以,由于 super() 是从
class Child,类名应该是隐含的。那我们为什么需要它??
*EDIT: - 将Child 作为参数提供给 super() 没有意义,因为它没有提供任何信息.. 我们可以使用 super(self).. 并且该方法会被搜索在超类中按照括号内给出的顺序..
【问题讨论】:
-
在 Python 3 中,您可以只使用
super()。 Python’s super() considered super! -
OOP。无法在办公室访问该链接.. :( 会在家里看到它..
标签: python python-2.7