28

假设我设置了以下类:

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() 来消除重复代码?

4

2 回答 2

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

然而,super引入了它自己的复杂性。参见例如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
于 2009-07-23T19:57:25.963 回答
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

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

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

于 2009-07-23T19:58:31.797 回答