Home

Tags

Python Singleton

2010-11-19 python singleton

class Singleton(object):
    _instance = None
    def __new__(self):
        if self._instance is None:
            self._instance = super(Singleton, self).__new__(self)
        return self._instance

if __name__ == '__main__':
    a=Singleton()
    b=Singleton()
    print id(a),id(b)
Результат
148991052 148991052


По идентификатору:
class Singleton(object):
    _instance = {}
    def __new__(self, id):
        try:
            return self._instance[id]
        except:
            d = super(Singleton, self).__new__(self)
            self._instance[id] = d
            return d

if __name__ == '__main__':
    a=Singleton('aaa')
    b=Singleton('bbb')
    c=Singleton('aaa')
    print id(a),id(b),id(c)
Результат
144925580 144925516 144925580


Общие параметры, но разные экземпляры
class Singleton(dict):
    _singltone = {}
    def __init__(self):
        self.__dict__ = self._singltone

a = Singleton()
b = Singleton()
a.var = 'hello'
print b.var # Выдаст 'hello'

comments powered by Disqus