Python 学习笔记: 单例模式

单例模式

通过重写__new__() 方法, 可以实现单例模式。

class Singleton:
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            cls._instance = object.__new__(cls, *args, **kw) #调用父类的构造方法去构造对象
        return cls._instance

one = Singleton()
two = Singleton()

two.a = 3
print(one.a)
# 3
# one和two完全相同,指向同一个对象,可以用id(), ==, is检测
print(id(one))
# 29097904
print(id(two))
# 29097904
print(one == two)
# True
print(one is two)

 

posted @ 2018-11-22 08:59  程序猿🌽  阅读(114)  评论(0编辑  收藏  举报