new method and singleton pattern in python

Keywords: Attribute

This article will briefly introduce the use of the new method, and then introduce the singleton mode.

__The new method init ializes the instance object. If it exists with the new method, it will execute the new method first,
A simple example:

class A:
	def __init__(self, name):
		self.name = name

	def __new__(cls, *args, **kw):
		print('bbb')
		return object.__new__(cls)

a = A('Zhang San')
print(a.name)

# Result
# bbb
# Zhang San

When do I use the new method? Reference link

Singleton mode
What is singleton mode? An object can only be instantiated once. From the second time, it is actually the first instantiated object, which is equivalent to the global. It can be judged according to the address

class A:
	def __init__(self, name):
		self.name = name

# Instantiate three objects
a = A('Zhang San')
b = A('Li Si')
c = A('Wang Wu')

# The printing result address is different, which instantiates three objects
print(a)  # <__main__.A object at 0x029CE5B0>
print(b)  # <__main__.A object at 0x00A009B0>
print(c)  # <__main__.A object at 0x00A00C10>

# Change the name of a to ahuang. Check the names of b and c
a.name = 'Huang'
print(a.name)  # Huang
print(b.name)  # Li Si
print(c.name)  # Wang Wu

It can be seen that instances are independent from each other.

In the singleton mode, all instantiated objects share a memory address. When an object changes some properties or methods, other objects will also change.
First, implement a single instance mode:

class A:
	__isinstance = False  # Set a private variable, which is not instantiated by default
	def __init__(self, name):
		self.name = name

	def __new__(cls, *args, **kwargs):
		if cls.__isinstance:  # If it's instantiated
			return cls.__isinstance  # Return instanced object
		cls.__isinstance = object.__new__(cls)  # Otherwise instantiate
		return cls.__isinstance  # Returns an instanced object

# Instantiate three objects
a = A('Zhang San')
b = A('Li Si')
c = A('Wang Wu')

# Print the address of three objects, and the result is one address
print(a)  # <__main__.A object at 0x00EFECF0>
print(b)  # <__main__.A object at 0x00EFECF0>
print(c)  # <__main__.A object at 0x00EFECF0>

# Change the name attribute of a object, and view the name attribute of B and C
a.name = 'Huang'
print(a.name)  # Huang
print(b.name)  # Huang
print(c.name)  # Huang

# Add an age attribute to b, and check the age attributes of a and C (yes, no, what is it)
b.age = 15
print(a.age)  # 15
print(b.age)  # 15
print(c.age)  # 15

This is a simple single example mode, which is more general

Posted by Apenvolkje on Sun, 17 Nov 2019 10:17:46 -0800