class Singleton(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs) return cls._instance if __name__ == '__main__': s1=Singleton() s2=Singleton() if(id(s1)==id(s2)): print "Same" else: print "Different"
输出结果: same
>>> help(id)
Help on built-in function id in module __builtin__:
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
说明,两个实例指向了同一个内存地址,为同一个对象。