python - 单例模式

单例模式:

class Foo:
    instance = None
    def __init__(self,name):
        self.name = name

    @classmethod
    def get_instance(cls):
        #cls 类名
        if cls.instance:
            return cls.instance
        else:
            obj = cls('google')
            cls.instance = obj
            return obj
obj1 = Foo.get_instance()
print(obj1)
obj2 = Foo.get_instance()
print(obj2)

out:

<__main__.Foo object at 0x00000000007D4278>
<__main__.Foo object at 0x00000000007D4278>

 

由上可知,obj1和obj2 内存地址都是一样的

posted @ 2016-06-26 18:41  unixfbi.com  阅读(157)  评论(0编辑  收藏  举报