What is a basic example of single inheritance using the super() keyword in Python?
假设我设置了以下类:
1 2 3 4 5 6 7 8 9 | class Foo: def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar: def __init__(self, frob, frizzle): self.frobnicate = frob self.frotz = 34 self.frazzle = frizzle |
在这个上下文中,如何使用super()(如果可以的话)来消除重复的代码?
假设您希望类栏在其构造函数中设置值34,那么这将起作用:
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 |
然而,
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): Foo.__init__(self, frob, frizzle) self.frotz = 34 self.frazzle = frizzle bar = Bar(1,2) print"frobnicate:", bar.frobnicate print"frotz:", bar.frotz print"frazzle:", bar.frazzle |
在python中>=3.0,如下所示:
1 2 3 4 5 6 7 8 9 | class Foo(): def __init__(self, frob, frotz) self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle) super().__init__(frob, 34) self.frazzle = frizzle |
阅读更多信息:http://docs.python.org/3.1/library/functions.html super
编辑:正如另一个答案所说,有时仅仅使用