python中单例模式的实现-通过闭包函数和魔术方法__new__实现单例
发布时间:2020-12-17 17:06:41 所属栏目:Python 来源:网络整理
导读:1、通过闭包函数实现单例模式: # 使用闭包函数实现单例 def single(cls,*args,** kwargs): instance = {} def get_instance(): if cls not in instance: instance[cls] = cls(*args,** kwargs) return instance[cls] return get_instance@single class Appl
1、通过闭包函数实现单例模式: # 使用闭包函数实现单例 def single(cls,*args,**kwargs): instance = {} def get_instance(): if cls not in instance: instance[cls] = cls(*args,**kwargs) return instance[cls] return get_instance @single class Apple: pass a = Apple() b = Apple() print(id(a)) print(id(b)) 2、通过python中魔术方法__new__实现单例模式: class Single: def __new__(cls,**kwargs): if not hasattr(cls,'_instance'): cls._instance = super(Single,cls).__new__(cls) return cls._instance s1 = Single() s2 = Single() print(id(s1)) print(id(s2)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |