Python basics 7 -- singleton mode

Posted by Copernicus on Thu, 20 Jan 2022 00:30:05 +0100

15 singleton mode

15.1 init and new methods

Perform steps

  1. Instantiate an object, execute the new method first, and return the object in the new method
  2. Then call the init method

15.1.1 __init__ method

__ init__ Is the construction method

In fact, the first method called is the new method, but in most cases, the new method is not used

class Test(object):
    def __init__(self):
        print("This is init method")

t = Test()

15.1.2 __new__ method

__new__

Step: when instantiating an object, the python interpreter will first call the new method to allocate space for the object, and then execute init to initialize the object

Function of new method

  1. Allocate space for objects in memory

  2. Returns a reference to an object

After obtaining the reference of the object, the python interpreter passes the reference as the first parameter to the init method

class Person(object):
    def __init__(self):
        print("This is init method")
    
    def __new__(cls,*args,**kwargs): #cls represents the class object itself
        print("This is new method",cls)
        
        
p = Person()
print(pe)
# Operation results
# This is the new method < class'__ main__. Person'> 
# None

be careful!!!: Not implemented init method

The first way to write

# Override new method
class Person(object): # new method provided by object
    def __init__(self):
        print("init")
        
    def __new__(cls,*args,**kwargs):#cls represents this class
        print("new")   # Execute the code of the new method first
        res = object.__new__(cls) #Call the new method of the parent class
        print(res) #res is the reference of the instantiated object
       	return res #Return the result after the instance

p2 = Person()

# Output results
# new
# <__main__.Person object at 0x000001C67F368A48>
# init

The second way to write

# Override new method
class Person(object): # new method provided by object
    def __init__(self):
        print("init")
        
    def __new__(cls,*args,**kwargs):#cls represents this class
        print("new")   # Execute the code of the new method first
       	return super().__new__(cls)

p2 = Person()

# Output results
# new
# <__main__.Person object at 0x000001C67F368A48>
# init

**When is the init method called automatically**

Called when instantiating

**The new method is used to create instance objects. Where does the new method come from**

From the object class

**What's in self**

self represents the instance object itself

15.2 introduction of singleton mode

Singleton pattern: it is a common software design pattern. The main purpose of this pattern is to ensure that only one instance of a class exists. When you want to have only one instance of a class in the whole system.

Method for implementing singleton mode

  1. Through @ classmethod
  2. Realized by decorator
  3. Pass__ new__ Realization (key points)
  4. Through the import module

Singleton pattern design process

  1. Define a class attribute with an initial value of None, which is used to record the reference of the singleton object
  2. Override new method
  3. Judge that if the class attribute is None, the object reference returned by the new method is saved.
  4. Returns the object reference recorded in the class property

15.3 use__ new__ Methods to implement the singleton mode

# An instance is instantiated no matter how many times it is instantiated

class Exam(object):
    # Record the first object reference created
    ins = None #Class properties
    
    def __init__(self):
        print("init method")
    
    def __new__(cls,*agrs,**kwargs):
        
        if cls.ins is None: #If empty, create a
            cls.ins = object.__new__(cls)
            
        return cls.ins #Returns a unique instance object

a = Exam()
print(a)
a2 = Exam()
print(a2)

15.4 realize the singleton mode through the decorator

It is realized through the method of decorator

class Exam(object):
    ins = None


def outer(fn): #Modified class name
    # Create a dictionary to hold the instance object of the class
    ins_dict = {} #{class name: instance, class name 2: instance 2}
    
    def inner():
        if fn not in ins_dict: #If there is no object in the dictionary
            # Create an object and save it in the dictionary
            res = fn()  #Instantiate an object
            ins_dict[fn] = res #Add information
        return ins_dict[fn]
    return inner

@outer
class Animal(object): #Class of singleton pattern
    pass

t1 = Animal()
print(t1)
t2 = Animal()
print(t2)


Topics: Python Design Pattern