class Player(): instance = None init_flag = False def __init__(self): if self.init_flag is False: print("初始化...") self.init_flag = True def __new__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__new__(cls) return cls.instance if __name__ == ‘__main__‘: p1 = Player() p2 = Player() p3 = Player() p4 = Player() print(p1) print(p2) print(p3) print(p4)
整体思路,用一个类属性来记录是否已经执行过这个函数,如果执行过了,改下类属性的值,然后判断这个值来进行单例模式
原文地址:https://www.cnblogs.com/blog-rui/p/9933410.html
时间: 2024-10-28 18:33:30