本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 | class MyObject1(object): def __init__(self): super(MyObject1, self).__init__() pass class MyObject2(object): def __init__(self, arg): super(MyObject2, self).__init__() pass |
我读过这样的python27代码,
我知道super的意思是父类构造函数,
但是我不明白为什么这两个类把自己叫做构造函数
它似乎没有任何实际效果。
这些是Python中一些非常基本的OO方法。在这里阅读的。
super() lets you avoid referring to the base class explicitly, which
can be nice. But the main advantage comes with multiple inheritance,
where all sorts of fun stuff can happen. See the standard docs on
super if you haven't already.
(从这个答案)
下面是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Foo(object): def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle): super(Bar, self).__init__(frob, frizzle) self.frotz = 34 self.frazzle = frizzle bar = Bar(1,2) print"frobnicate:", bar.frobnicate print"frotz:", bar.frotz print"frazzle:", bar.frazzle |
您可以看到
测试代码,它会更有意义。