Jeremy Jeremy - 1 year ago 74
Python Question

How do I initialize the base (super) class in Python?

In Python, consider I have the following code:

>>> class SuperClass(object):
def __init__(self, x):
self.x = x

>>> class SubClass(SuperClass):
def __init__(self, y):
self.y = y
# how do I initialize the SuperClass __init__ here?

How do I initialize the
SuperClass __init__
in the subclass? I am following the Python tutorial and it doesn't cover that. When I searched on Google, I found more than one way of doing. What is the standard way of handling this?

Answer Source

Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from 'object' and are what you are using, and invoke their base class through super(), e.g.

class X(object):
  def __init__(self, x):

  def doit(self, bar):

class Y(X):
  def __init__(self):
    super(Y, self).__init__(123)

  def doit(self, foo):
    return super(Y, self).doit(foo)

Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.

For completeness sake, old-style classes call base methods explicitly using the base class, i.e.

def doit(self, foo):
  return, foo)

But since you shouldn't be using old-style anymore, I wouldn't care about this too much.

Python 3 only knows about new-style classes (no matter if you derive from object or not).