单例模式
第一阶段:普通模式
NAME = 'PLF'
AGE = 18
class Foo:
__instance = None
def __init__(self,name,age):
self.name = name
self.age = age
@classmethod
def func(cls):
if cls.__instance:
return cls.__instance
obj = cls(NAME,AGE)
cls.__instance = obj
return obj
one = Foo.func()
two = Foo.func()
three = Foo.func()
four = Foo.func()
print(id(one))
print(id(two))
print(id(three))
print(id(four))
1734533208384
1734533208384
1734533208384
1734533208384
总结:通过类属性保存创建的第一个对象,之后对类属性进行判断,类属性有值则一直沿用类属性的值(对象),没有则创建。
第二阶段:进阶
NAME = 'PLF'
AGE = 18
def deco(cls):
cls.__instance = cls(NAME,AGE)
def wrapper(*args,**kwargs):
if len(args) == 0 and len(kwargs) == 0:
return cls.__instance
res = cls(*args,**kwargs)
return res
return wrapper
@deco
class Foo:
__instance = None
def __init__(self,name,age):
self.name = name
self.age = age
ori = Foo() # Foo() = wrapper() ,没有加参数使用默认初始化
print(ori.name,ori.age)
one = Foo('LT',100) # 用户添加参数,则使用用户的参数进行初始化,不使用
print(one.name,one.age)
PLF 18
LT 100
第三阶段:最正宗的模式
NAME = 'PLF'
AGE = 18
class Foo(type):
def __init__(self,class_name,class_bases,class_dict):
super().__init__(class_name,class_bases,class_dict)
self.instance = self(NAME,AGE)
def __call__(self, *args, **kwargs):
if self.instance:
return self.instance
obj = object.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
class Person(metaclass=Foo):
instance = None
def __init__(self,name,age):
self.name = name
self.age = age
def run(self):
print("run")
def eat(self):
print("eat")
one = Person('zhangsan',20)
two = Person()
three = Person()
print(one)
print(two)
print(three)
<__main__.Person object at 0x000002A4FC2741D0>
<__main__.Person object at 0x000002A4FC2741D0>
<__main__.Person object at 0x000002A4FC2741D0>
通过类属性将我们自己的实例对象保留下来,之后再创建就一直使用类属性中的实例对象