What is the purpose of calling __init__ directly?

Ari picture Ari · Apr 21, 2013 · Viewed 19.5k times · Source

I am having a hard time figuring out the purpose some code that I've come across.

The code has a class Foo, which has an __init__ method that takes multiple arguments. From what I've learned of Python so far, by calling Foo('bar'), it will pass this string as a parameter to __init__ (which I think is supposed to be the equivalent of a constructor).

But the issue I am having is that the code I am looking at is calling Foo.__init__('bar') directly. What is the purpose of this? I almost feel that I am missing some other purpose behind __init__.

Answer

Raymond Hettinger picture Raymond Hettinger · Apr 21, 2013

The __init__() method gets called for you when you instantiate a class. However, the __init__() method in a parent class doesn't get called automatically, so need you to call it directly if you want to extend its functionality:

class A:

     def __init__(self, x):
          self.x = x

class B(A):

     def __init__(self, x, y):
          A.__init__(self, x)
          self.y = y

Note, the above call can also be written using super:

class B(A):

     def __init__(self, x, y):
          super().__init__(x)
          self.y = y

The purpose of the __init__() method is to initialize the class. It is usually responsible for populating the instance variables. Because of this, you want to have __init__() get called for all classes in the class hierarchy.