在Python中使用super()关键字的单继承的基本示例是什么?

lfa*_*one 27 python inheritance constructor super

假设我已经设置了以下类:

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
Run Code Online (Sandbox Code Playgroud)

我怎么能(如果我可以)在这个上下文中使用super()来消除重复的代码?

ire*_*ses 29

假设您希望类Bar在其构造函数中设置值34,这将起作用:

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
Run Code Online (Sandbox Code Playgroud)

但是,super介绍了它自己的并发症.参见例如超认为有害的.为了完整性,这里是没有的等效版本super.

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
Run Code Online (Sandbox Code Playgroud)

  • 是的,这也会奏效,而且会更清洁.这个例子非常人为(在构造函数中设置一个常量),但我试图保持尽可能接近原始值. (2认同)

JAB*_*JAB 26

在Python> = 3.0中,像这样:

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
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多内容:http://docs.python.org/3.1/library/functions.html#super

编辑:正如在另一个答案中所说,有时只是使用Foo.__init__(self, frob, 34)可能是更好的解决方案.(例如,在处理某些形式的多重继承时.)

  • 为了清楚起见,这只是python> = 3.0.对于较老的蟒蛇(但只有那些具有"新式类"的蟒蛇),@ ire_and_curses答案描述了需要做什么. (9认同)