Python3 basics (12)-singleton mode

1. The __new__ method is the same as the __init__ method, which is automatically called by the system parser. The __new__ method must have a return value, which is an object instance that returns it.

class User(object):
	def __init__(self, username, password):
		self.username = username
		self.password = password
		print("对象已经构建好了,由解释器自动回调的init方法,对象初始化")

#new方法是当对象构建的时候由解释器自动回调的方法,该方法必须返回当前类的对象,重写的是父类的静态方法
	def __new__(cls, username, password):    #如果初始化方法传入了其它参数,在这里也需要加入其它的方法
		print("User类的对象开始构建")
		return object.__new__(cls)    #如果没有返回实例,代表根本没有创建实例。

	def __str__(self):
	    return "名称:%s,密码:%s"%(self.username, self.password)

u = User("zs", "123")
print(u)

Insert picture description here

2. Singleton mode
Take a common example of singleton mode. Every computer we use has a recycle bin. In the entire operating system, there can only be one instance of the recycle bin, and the entire system uses this unique instance, and The recycle bin provides its own examples. Therefore, the recycle bin is an application of singleton mode.
Make sure that there is only one instance of a certain class, and instantiate it by itself and provide this instance to the entire system. This class is called a singleton class, and the singleton mode is an object creation mode.
Do a test:

u1 = User("zs", "123")
u2 = User("ls", "456")
print(u1 == u2)    #==判断表达式如果返回True,这两个对象是一个对象,并且内存地址相同
print("u1对象的内存地址:%s,u2对象的内存地址:%s"%(id(u1), id(u2)))
以上结果可以看出,执行结果为False,是不同的对象。

The first method (pseudo singleton mode):
If you want to form a singleton mode, you need to create a private global variable and a class method or static method in the User class:
__instance = None #Private global variables are also class attributes, class attributes It needs to be called by the cls class name. The object properties need to be called through the self object.

@classmethod
def get_instance(cls, username, password):    #如果对象创建时,有其它参数传入,则此函数也必须要带上其它参数
if not cls.__instance:    #判断私有变量是否为空
cls.__instance = User(cls, username, password)    #如果为空,则为私有变量重新赋值
return cls.__instance    #返回单例对象

The calling method is changed to:

u1 = User.get_instance("zs", "123")    #调用类方法进行初始化
u2 = User.get_instance("ls", "456")
print(u1 == u2)    #==判断表达式如果返回True,这两个对象是一个对象,并且内存地址相同
print("u1对象的内存地址:%s,u2对象的内存地址:%s"%(id(u1), id(u2)))

Note: This method cannot prevent the user from actively calling User() for instantiation. This will result in not a singleton mode. And there is an advantage here, that is, no matter how many objects are created, they are all the same object, and the parameters passed in by this object are subject to the parameters passed in when the object is instantiated for the first time, that is, zs and 123. The parameters passed in during instantiation will not be assigned to the object parameters.

The second method:
Principle: The __new__ method is a method to create a class instance, and it is automatically called back by the system. If it is guaranteed that this method returns the same instance, the singleton mode can be achieved.

__instance = None
def __new __(cls, username ,password)
if not cls.__instance:    #判断私有变量是否为空
cls.__instance = object.__new__(cls)    #如果为空,则为私有变量重新赋值,保证object.__new__()方法只执行一次
return cls.__instance    #返回单例对象

u1 = User("zs", "123")
u2 = User("ls", "456")
print(u1 == u2)    #==判断表达式如果返回True,这两个对象是一个对象,并且内存地址相同
print("u1对象的内存地址:%s,u2对象的内存地址:%s"%(id(u1), id(u2)))

It can be seen from the above results that the execution result is False, which is a different object.
Note: The advantage of this method is that as long as the user creates an object, it is a singleton mode of the same object. The value of the parameter inside is just the opposite of the parameter value obtained when the singleton is created in the first method. Because this method calls the __new__ method every time it is instantiated, and then it calls the __init__ method, which leads to the assignment of object parameters each time it is instantiated, which results in each instantiation time , Will change the value of the parameter in the object. Therefore, the parameters of the final state of the object are based on the parameters passed in the last instantiation. Of course, if you instantiate the object once before each call, you will get the parameter value just passed in.
Of course, this method cannot prevent users from cheating. Users can also obtain an object through u3 = object. new (User), but this method does not automatically call the initialization method __init__.

3. Tips:
1) As long as there is a default incoming method, it is an ordinary member method

Author: Cangshuipu witch cloud
blog: http://blog.csdn.NET/amir_zt/
more original, please indicate the source, thank you.
https://blog.csdn.net/amir_zt/article/details/84646228

Guess you like

Origin blog.csdn.net/u011635351/article/details/84646228