假设我设置了以下类:
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()来消除重复的代码?
答案 0 :(得分: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 considered harmful。为了完整起见,这是没有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
答案 1 :(得分: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)
可能是更好的解决方案。 (例如,在处理某些形式的多重继承时。)