Why is __init__() 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.

raja
Published on 23-May-2019 18:57:17
Advertisements