Python-单例实现

"""
__new__函数:在实例化开始之后,在调用 __init__() 方法之前,Python 首先调用 __new__() 方法
"""


# 单例1
class Singleton1(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_inst'):
            cls._inst = super(Singleton1, cls).__new__(cls)  # 相当于object.__new__(cls)
        return cls._inst


# 单例2
class Singleton2(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_inst'):
            cls._inst = object.__new__(cls)
        return cls._inst

# 自定义单列
class Person(object):
    def __new__(cls, name, age):
        if 0 < age < 150:
            return super(Person, cls).__new__(cls)  # return object.__new__(cls)
        else:
            return None

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f'{self.__class__.__name__}{self.__dict__}'


if __name__ == '__main__':
    print(Singleton1())
    print(Singleton1())
    print(Singleton2())
    print(Singleton2())

    print(Person('Tom', 10))
    import time
    time.sleep(5)
    print(Person('Mike', 200))
原文地址:https://www.cnblogs.com/shuzf/p/14654429.html