python object creation and instance generation times

pyhton uses __new__ to create objects (__new__ is equivalent to the construction function in Java),

After the object is created, the __init__ method will be called immediately to initialize the object. The __init__ method has a parameter self that is the object created by __new__ just now. By assigning attributes to the object in the __init__ method, or adding attributes to the dynamic line object and assigning values

class test(object):
    count = 0
    def __new__(cls, *args, **kwargs):
        test.count += 1
         if test.count >2 :
            raise Exception( " more than 2 instantiations " )
         return super(test, cls). __new__ (cls)
     def  __init__ (self,a):
        self.a = a


test0 = test('c')
test1 = test('b')
# test3 = test('a')

print(test1.count)
del test1
of the test0
print(test1.count)

When del objectname is used, the instance of this object is destroyed, and when the reference count of this object is 0, it will be recycled

Guess you like

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