Let's say I have the following classes set up:
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
How can I (if I can at all) use super() in this context to eliminate the duplicate code?
解决方案
In Python >=3.0, like this:
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
EDIT: As said in another answer, sometimes just using Foo.__init__(self, frob, 34) can be the better solution. (For instance, when working with certain forms of multiple inheritance.)