单例模式

单例模式 :是指一个类只会有一个实例,主要是用来控制对资源的访问;
__new__ 中保证了每次实例化时都返回同一个实例,但是 __init__方法却每次实例化时都执行,因此可以添加一个参数 来指明实例化的执行状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Singleton:
    inited = False

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            cls._instance = super().__new__(cls)
        else:
            cls.inited = True

        return cls._instance


class Person(Singleton):
    def __init__(self, name, age=80):
        if not self.inited:
            self.name = name
            self.age = age


a = Person("leon", 23)
b = Person("tom", 27)
print(a.name) #  >>> "leon"
print(b.name) #  >>> "leon"