class MusicPlayer(object):
"""单例类实现"""
# 定义一个类属性记录第一次创建的实例对象的引用
instance = None
def __new__(cls, *args, **kwargs):
# 1. 判断类属性是否为空
if not cls.instance:
# 2. 如果类属性为空,调用父类的__new__方法,为对象在内存中分配空间,创建一个对象,并将对象的引用保存到类属性中
cls.instance = super().__new__(cls)
# 3. 将类属性保存的实例对象的引用返回
return cls.instance
# 创建一个实例
player1 = MusicPlayer()
print(player1)
# 在创建一个实例,两个实例的引用输出结果是一致的,这就是单例
player2 = MusicPlayer()
print(player2)
python中如何实现单例设计模式?
猜你喜欢
转载自blog.csdn.net/weixin_42289273/article/details/103433692
今日推荐
周排行