22.单元模式

【一】单例模式

  • 让一个类只创建一个对象,即所有对象都是一样的

1)元类

class MyType(type):
    def __init__(cls, name, bases, name_space):
        # 给自己的类加一个属性:instance初始值None
        cls.instance = None
        super().__init__(name, bases, name_space)
    def __call__(self, *args, **kwargs):
        obj = super.__call__(*args, **kwargs)
        if self.instance:
            return self.instance
        else:
            self.instance = obj
            return self.instance
        
class Student(metaclass=MyType):
    ...
    
st1 = Student()
st2 = Student()
print(id(st1))  # 1958218485568
print(id(st2))  # 1958218485568

2)模块

eg
  __init__.py
  common.py
singleton.py 
# __init__.py
from .common import Student
stu = Student()
# common.py
class Student():
    ...
# singleton.py
from eg import stu

st1 = stu
st2 = stu
print(id(st1))  # 2857417634960
print(id(st2))  # 2857417634960

3)装饰器

def outer(cls):
    instance = {'cls': None}
    def inner(*args, **kwargs):
        nonlocal instance
        if not instance.get('cls'):
            instance['cls'] = cls(*args, **kwargs)
        return instance['cls']
    return inner

@outer
class Student:
    def __init__(self, name):
        self.name = name

st1 = Student('a')
st2 = Student('b')
print(st1, id(st1))
print(st2, id(st2))
posted on 2024-05-10 15:22  晓雾-Mist  阅读(9)  评论(0)    收藏  举报