# Initialize the singleton object only once class MusicPlayer(object): instance = None __first_load = True def __new__(cls, *args, **kwargs): # When creating an object, the new method will be called automatically # Determine whether the singleton object is empty if cls.instance is None: cls.instance = super().__new__(cls) return cls.instance def __init__(self): if MusicPlayer.__first_load is True: print("Initialize the music player") MusicPlayer.__first_load = False player_one = MusicPlayer() player_two = MusicPlayer() print(player_one) print(player_two)
Quantitative trading of python basics-singleton writing (initialize only once)
Guess you like
Origin blog.csdn.net/Michael_234198652/article/details/109156947
Recommended
Ranking