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)
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)
可能是更好的解决方案.(例如,在处理某些形式的多重继承时.)