python 手写单例模式

1. 单例模式代码

# 单例模式
class SingleTon:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            _instance = super().__new__(cls, *args, **kwargs)
            cls._instance = _instance
        return cls._instance

或者

class SingleTon(object):
    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(SingleTon, "_instance"):  # 反射
            SingleTon._instance = object.__new__(cls)
        return SingleTon._instance


obj1 = SingleTon()
obj2 = SingleTon()
print(obj1 == obj2)

2. 验证单例模式

# 单例模式
class SingleTon:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            _instance = super().__new__(cls, *args, **kwargs)
            cls._instance = _instance
        return cls._instance


# 验证单列模式
class MyClass(SingleTon):
    pass


c1 = MyClass()
c2 = MyClass()

print(id(c1))
print(id(c2))
print(c1 is c2)

你可能感兴趣的:(python)