Python object-oriented singleton (3)

Singleton

aims

  • Singleton design pattern
  • new method
  • Singleton in Python

01. Singleton design pattern

Design Patterns

Design pattern is a summary of previous work and refining, generally, people are widespread models are designed for a particular problem sophisticated solutions

The use of design patterns is to reusable code, make it easier for others to understand, and ensure code reliability

Singleton design pattern

  • Purpose-the object created by the class has only one instance in the system
  • The memory address of the object returned by the class name () is the same every time

Application scenarios of singleton design pattern

  • Music player
  • Recycle Bin Object
  • Printer object
    ...

02. _ new _ method

When using the class name () to create an object, the Python interpreter first calls the _ new _ method to allocate space for the object

_ new _ is a built-in static method provided by the object base class, which has two main functions:

  • Allocate space for objects in memory
  • Returns a reference to the object

After Python interpreter obtained reference object, the reference as the first parameter passed to _ the init _ Method

The code to rewrite the _ new _ method is very fixed!

To rewrite _ new _ method must return super()._ new _(cls)

Otherwise, the Python interpreter cannot get a reference to the allocated object, and it will not call the object's initialization method.

Note: _ new _ is a static method, you need to actively pass the cls parameter when calling
Insert picture description here

Sample code

class MusicPlayer(object):def __new__(cls, *args, **kwargs):
       # 如果不返回任何结果,
       return super().__new__(cls)def __init__(self):
       print("初始化音乐播放对象")
​
player = MusicPlayer()print(player)

03. Singleton in Python

  • Singleton-Let the object created by the class have only one instance in the system
    a, define a class attribute, the initial value is None, used to record the reference of the singleton object
    b, override the new method
    c, if the class attribute is None, call the parent class method to allocate space, and record the result in the class attribute
    d, return the object reference recorded in the class attribute
    Insert picture description here
class MusicPlayer(object):# 定义类属性记录单例对象引用
   instance = Nonedef __new__(cls, *args, **kwargs):# 1. 判断类属性是否已经被赋值
       if cls.instance is None:
           cls.instance = super().__new__(cls)# 2. 返回类属性的单例引用
       return cls.instance


Initialization is performed only once

  • Every time you use the class name () to create an object, the Python interpreter will automatically call two methods:
    _ new _ allocating space
    _ init _ object initialization
  • After transforming the new method in the previous section , every time you get a reference to the object created for the first time
  • But: the initialization method will be called again

demand

  • Let the initialization action be executed only once

Solution

1. Define a class attribute init_flag to mark whether the initialization action has been performed, the initial value is False

2. In the _ init _ method, judge the init_flag, if it is False, perform the initialization action

3. Then set init_flag to True

4. In this way, when the init method is automatically called again , the initialization action will not be executed again

class MusicPlayer(object):# 记录第一个被创建对象的引用
   instance = None
   # 记录是否执行过初始化动作
   init_flag = Falsedef __new__(cls, *args, **kwargs):# 1. 判断类属性是否是空对象
       if cls.instance is None:
           # 2. 调用父类的方法,为第一个对象分配空间
           cls.instance = super().__new__(cls)# 3. 返回类属性保存的对象引用
       return cls.instance
​
   def __init__(self):if not MusicPlayer.init_flag:
           print("初始化音乐播放器")
​
           MusicPlayer.init_flag = True
​
​
# 创建多个对象
player1 = MusicPlayer()
print(player1)
​
player2 = MusicPlayer()
print(player2)

Guess you like

Origin blog.csdn.net/weixin_42272869/article/details/113486542