首页 > 编程语言 > 详细

Python-单例实现

时间:2021-04-13 23:21:45      阅读:26      评论:0      收藏:0      [点我收藏+]

 

 

"""
__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))

 

Python-单例实现

原文:https://www.cnblogs.com/shuzf/p/14654429.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!