15 singleton mode
15.1 init and new methods
Perform steps
- Instantiate an object, execute the new method first, and return the object in the new method
- 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
-
Allocate space for objects in memory
-
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
- Through @ classmethod
- Realized by decorator
- Pass__ new__ Realization (key points)
- Through the import module
Singleton pattern design process
- Define a class attribute with an initial value of None, which is used to record the reference of the singleton object
- Override new method
- Judge that if the class attribute is None, the object reference returned by the new method is saved.
- 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)