Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of calling __init__ directly?

Tags:

python

init

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__.

like image 500
Ari Avatar asked Apr 21 '13 00:04

Ari


People also ask

What is the purpose of __ init __ method?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.

What is the use of __ call __ in Python?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

Is __ init __ called automatically?

important to remember : The __init__ function is called a constructor, or initializer, and is automatically called when you create a new instance of a class.

What is __ init __( self in Python?

The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can easily access all the instances defined within a class, including its methods and attributes. init. __init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor.


1 Answers

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.

like image 66
Raymond Hettinger Avatar answered Sep 29 '22 23:09

Raymond Hettinger