SoFunction
Updated on 2024-12-20

Difference and connection between __new__ and __init__ in Python

The difference between __new__ and __init__ is mainly:

__new__ is responsible for object creation and __init__ is responsible for object initialization.

__new__: called when creating an object, returns an instance of the current object

__init__: called after creating an object, initializes some instances of the current object, no return value

1. In a class, if both __new__ and __init__ exist, __new__ is called first.

class ClsTest(object):    def __init__(self):        print("init")    def __new__(cls,*args, **kwargs):        print("new")ClsTest()

Output:

new

2. If __new__ returns an instance of an object, __init__ is called implicitly.

Code Example:

class ClsTest(object):    def __init__(self):        print ("init")    def __new__(cls,*args, **kwargs):        print ("new %s"%cls)        return object.__new__(cls, *args, **kwargs)ClsTest()

Output:

new <class '__main__.ClsTest'>init

3. The __new__ method returns the constructed object; __init__ does not. __init__ has no return value.

class ClsTest(object):     def __init__(cls):              = 2             print ("init")             return clsClsTest()

Output:

initTraceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: __init__() should return None, not 'ClsTest'

4. If __new__ does not correctly return an instance of the current class cls, then __init__ will not be called, even if it is an instance of the parent class.

class ClsTest1(object):    passclass ClsTest2(ClsTest1):    def __init__(self):        print ("init")    def __new__(cls,*args, **kwargs):        print ("new %s"%cls)        return object.__new__(ClsTest1, *args, **kwargs)b=ClsTest2()print (type(b))

Output:

new <class '__main__.ClsTest2'>

<class '__main__.ClsTest1'>

Knowledge Points:

1. New classes inheriting from object have __new__.

2. __new__ must have at least one parameter cls, on behalf of the class to be instantiated, this parameter is automatically provided by the Python interpreter at the time of instantiation, __new__ must have a return value to return to the instance of the instantiation, you can return the instance of the parent class __new__ out of the instance, or directly object of the instance of the __new__ out of the instance

3. __init__ has one parameter self, which is the instance returned by this __new__, __init__ can complete some other initialization actions on the basis of __new__, __init__ does not need to return value

4. If __new__ returns an instance of an object, it implicitly calls __init__.

For more information about the difference and connection between __new__ and __init__ in Python, check out the following related links