python单例模式简单例子

发布时间:2020-10-29编辑:脚本学堂
一个python单例模式的例子,有关python设计模式的入门实例,需要的朋友参考下。

例子,python单例模式
 

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.)

说明,两个实例指向了同一个内存地址,为同一个对象。