python中单例模式的实现-通过闭包函数和魔术方法__new__实现单例模式
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, *args, **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))
相关推荐
yuwinter 2020-10-14
归去来兮 2020-09-18
Ericbig 2020-07-19
chaigang 2020-06-27
yogoma 2020-06-14
Andrewjdw 2020-05-27
jokerdby 2020-05-19
Kingonion 2020-04-23
ELEMENTS爱乐冬雨 2020-04-21
sunlizhen 2020-04-17
LczPtr 2020-04-14
Livis的开发之路 2020-03-11
Airuio 2020-03-06
Livis的开发之路 2020-02-28