Why __init__ is Always Called After New in Python



Python is having special type of methods called magic methods named with preceded and double underscores.

if we want to talk about magic method __new__ then obviously will also need to talk about __init__ method. The magic method __new__ will be called when instance is being created.where as __init__ method will be called to initialize instance when you are creating instance.

Example

 Live Demo

class X():
_dict = dict()

def __new__(self):
if 'data' in X._dict:
print ("new instance Exists")
return X._dict['data']
else:
print ("magic method New")
return super(X, self).__new__(self)

def __init__(self):
print ("instantiation")
X._dict['data'] = self
print ("")

a1 = X()
a2 = X()
a3 = X()

Output

magic method New
instantiation

new instance Exists
instantiation

new instance Exists
instantiation

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.

Updated on: 2019-07-30T22:30:26+05:30

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements