Understanding the Singleton Pattern

# First understand what happens when you use new when the object class instantiates an object
# class Person():
#     def __init__(self):
# print('This is the init method')
#
#
# a = Person() # When the new method of the object is not overridden and the singleton mode is not adopted, each time an object is instantiated
# b = Person() # object's new method will create a memory address to store the instantiated object
# print(id(a)) # So the memory address of each instantiated object is different, the init initialization method will be called respectively to initialize
# print(id(b))

# Second, override the new method in the subclass
class Person(object):
    zheshibenshen = None
    def __new__(cls):
        if cls.zheshibenshen == None:
            cls.zheshibenshen = super().__new__(cls)
        return cls.zheshibenshen

    def __init__(self):
        print('This is the init method')


a = Person() # This rewrites the new method of the parent class object, so that this class always returns zheshibenshen (that is, itself) every time an object is instantiated
b = Person() # When instantiated for the first time, here is to re-call the new method of object to create a memory address to store the instance object
                 # Without rewriting new, the object will also execute the super().__new__(Person) method to create a memory address to store the instance
print(id(a)) # Then assign it to zheshibenshen and return it, they are actually the objects when the class was first instantiated
# # Up to this point, the process is the same as when the new method is not rewritten. The point is when the object is instantiated by the latter class
# # That is to say, when the object is instantiated in the future, every time new will judge the instantiated object, whether it is empty or not, it will return itself if it is not empty.
print(id(b)) # So every time an object is instantiated, (after rewriting) every time the new method returns the first instantiated object
                 # both point to the first instantiated memory address, so no matter how many objects are instantiated later, they are the same thing in the same memory address

  

Guess you like

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