__new__ in Python

Python Methods and Functions

Note. To learn more about magic methods,

# Python program for
# demonstrate __new__

 
# don't forget the base object

class A ( object ):

  def __ new __ ( cls ):

print ( " Creating instance " )

  return super (A, cls ) .__ new __ ( cls )

 

def __ init __ ( self ):

print ( "Init is called" )

 
A ()

Exit:

 Creating instance Init is called 

The above example shows that the __new__ method is called automatically when the class name is called, whereas the __init__ method is called every time a class instance is returned by the __new__ method, passing the returned __init__ instance as the self , so even if you were to save the instance somewhere globally / statically and return it every time from __new__, then __init__ will be called every time you do exactly that.

This means that if super is omitted for the __new__ method, the __init__ method will not be executed. Let's see if this is the case.

Exit :

 Creating instance None 

In the above example, you can see that the method __init__ is not called and the instance value evaluates to None because the constructor returns nothing. Let's see what happens if both __new__ and __init__ return something.

# Python program for
# demonstrate __new __

 

class A ( object ):

def __ new __ ( cls ):

print ( "Creating instance" )

 

# It's not called

  def __ init __ ( self ):

print ( " Init is called " )

  

print (A ())

# Python program for
# demonstrate __new__

 

class A ( object ):

# new method that returns a string

  def __ new __ ( cls ) :

print ( "Creating instance" )

  return " Python.Engineering "

  

class B ( object ):

# init method returning a string

def __ init __ ( self ):

print ( "Initializing instance" )

return "GeeksforGeeks"

 

print ( A ()) < / p>

print (B ())

Exit:

 Creating instance Python.Engineering Initializing instance 
 Traceback ( most recent call last): File "/home/62216eb30d3856048eff916fb8d4c32d.py", line 17, in print (B ()) TypeError: __init __ () should return None, not 'str' 

This TypeError is thrown a handler that calls the __init__ method, and it doesn't make sense to return anything from the __init__ method, since its purpose is simply to change the fresh state of the newly created instance.

Let's try an example where the __new__ method returns an instance of another class ... 
Example :

# Python program for
# demonstrate the __new__ method

 
# the class whose object
# returned

class Python.Engineering ( object ):

def __ str __ ( self ):

return "GeeksforGeeks"

 
# class returning the object
# different class

class Geek ( object ):

  def __ new __ ( cls ):

return Python.Engineering ()

 

def __ init __ ( self ):

print ( " Inside init " )

 

print (Geek ())

Exit:

 Python.Engineering 




Get Solution for free from DataCamp guru