python实现单例模式

# coding: utf-8

class Single(object):
    __instance = None
    def __new__(cls):
        if not cls.__instance:
            # cls.__instance = Single() # 错误写法
            
            # 写法一
            # cls.__instance = super(Single, cls).__new__(cls)
            
            # 写法二
            cls.__instance = object.__new__(cls)
        return cls.__instance
A = Single()
B = Single()
print id(A)  # 140658853884880
print id(B)  # 140658853884880

猜你喜欢

转载自blog.csdn.net/xin_yun_jian/article/details/80791978