python __new__ __init__ difference

  1. parameter
    • The first placeholder parameter of __new__ is the class object
    • The first placeholder parameter of __init__ is the instance object of the class
    • Other parameters should be the same
  2. effect
    • __new__ is used to create an instance, execute __init__ on the returned instance, if no instance is returned then __init__ will not be executed
    • __init__ is used to initialize instances, set properties and other initialization actions

 

  __new__ is the real constructor in Python (create and return an instance), through which an instance object corresponding to "cls" can be generated, so the "new" method must have a return.

  __init__ is an initialization method, "self" represents the instance object generated by the class, and "init" will perform the corresponding initialization operation on this object.

 
 
class A(object):
    def __init__(self,*args,**kwargs):
        print ("calling __init__ from %s" % self.__class__)

    def __new__(cls,*args,**kwargs):
        obj = object.__new__(cls,*args,**kwargs)
        print ("calling __new__ from %s" % obj.__class__)
        return obj

class B(A):
    def __init__(self,*args,**kwargs):
        print ("calling __init__ from %s" % self.__class__)
    def __new__(cls,*args,**kwargs):
        obj = object.__new__(A,*args,**kwargs)
        print ("calling __new__ from %s" % obj.__class__)
        return obj

b=B()
print (type(b))

In B's "new" method, an instance of A is created by "obj = object.new(A, *args, **kwargs)", in this case, B's "init" function will not be called call to.

The output is:

calling __new__ from <class '__main__.A'>
<class '__main__.A'>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324844144&siteId=291194637