单列模式
#导包方式引入 #new方法实现 class Student(): def __new__(self): if not hasattr(self,'instance'): self.instance =super(Student,self).__new__(self) return self.instance a = Student() b = Student() print(id(a),id(b)) class Cat(): def __new__(self): if not hasattr(self,'instance'): self.instane = super(Cat,self).__new__() return self.instane class Person(): def __new__(self): if not hasattr(self,'instance'): self.instance = super(Person,self).__new__() return self.instance #装饰器 def singleton(cls,*arg,**kwargs): instance = {} def _singleton(): if cls not in instance: instance[cls] = cls(*arg,**kwargs) return instance[cls] return _singleton @singleton class Box(): pass s = Box() m = Box() print(id(s),id(m))
posted on 2020-04-24 21:36 __director 阅读(110) 评论(0) 编辑 收藏 举报