What is a basic example of single inheritance using the super() keyword in Python?

lfaraone picture lfaraone · Jul 23, 2009 · Viewed 43.3k times · Source

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?

Answer

ire_and_curses picture ire_and_curses · Jul 23, 2009

Assuming you want class Bar to set the value 34 within its constructor, this would work:

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

However, super introduces its own complications. See e.g. super considered harmful. For completeness, here's the equivalent version without 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