python Singleton pattern,pythonsingleton,Python singl


Python singleton pattern implement

# override __new__ methodclass Singleton(object):    ''' A Pythonic Singleton '''    def __new__(cls,*args,**kwargs):        if '_inst' not in vars(cls):            cls._inst = object.__new__(cls,*args,**kwargs)                    return cls._inst# use decoratorclass SingleDecorator(object):    def __init__(self, cls):        self.cls = cls        self._inst = None    def __call__(self, *args, **kwargs):        if not self._inst:            self._inst = self.cls(*args, **kwargs)        return self._instclass Example(object):    passExample = SingleDecorator(Example)a = Example()b = Example() #use module feature#This implement is recommendimport sysclass _single(object):    passsys.modules[__name__] = _single()#share status

评论关闭