【Python】单例模式

单例


class MusicPlayer(object):

    instance = None

    def __new__(cls, *args, **kwargs):

        if cls.instance is not None:
            return cls.instance
        else:
            cls.instance = super().__new__(cls)
            return cls.instance

player1 = MusicPlayer()
print(player1)

player2 = MusicPlayer()
print(player2)

单例初始化一次

class MusicPlayer(object):

    instance = None
    init_flag = False

    def __new__(cls, *args, **kwargs):

        if cls.instance is not None:
            return  cls.instance
        else:
            return super().__new__(cls)

    def __init__(self):

        if MusicPlayer.init_flag:
            return MusicPlayer.instance
        else:
            print("初始化播放器")
            MusicPlayer.init_flag = True

player1 = MusicPlayer()
print(player1)

player2 = MusicPlayer()
print(player2)

你可能感兴趣的:(【Python】单例模式)