#!/usr/bin/env python class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Logger(object): __metaclass__ = Singleton def __init__(self, id, name): self.id = id self.name = name def display(self): print self.id print self.name ######## test ########### log1 = Logger(id = 1, name = '1') log2 = Logger(id = 2, name = '2') print log1 is log2 log1.display() log2.display()
https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python