Avatar ·

Python中的单例模式

📁 python, 人工智能

用Wiki()实现了singleton

我的代码:

class SpriteManager(object):    def __new__(cls):        if not hasattr(cls, 'instance'):             cls.instance = super(SpriteManager, cls).__new__(cls)        retu cls.instance    def __init__(self):        self.setSprite = set()

每次调用SpriteManager()时都会调用构造函数。根据singleton的概念,初始化应该在第一次调用时只执行一次。如何让构造函数只调用一次?