python单例模式的几种写法

python单例模式的几种写法,第1张

1. 利用__metaclass__

这种写法的好处是,一处声明,到处引用,只要是想弄成单例的,直接设置就可以了,废话不说上代码

# 注意,继承type
class Singleton(type):

	def __call__(cls, *args, **kwargs):
		if not hasattr(cls, '_instance'):
			cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
		return cls._instance


class Test(object):
	# __metaclass__
	__metaclass__ = Singleton

t1 = Test()
t2 = Test()
print t1 == t2

想深入了解, 可以搜索python type详解,以及python类初始化的流程

2. 每个类单独写

这种写法好处是,可以给自己的单例类加上特有的逻辑

class MyTest(object):
	def __new__(cls, *args, **kwargs):
		if not hasattr(cls, '_instance'):
			# 两种写法,实际上都是为了调用object.__new__
			cls._instance = object.__new__(cls, *args, **kwargs)
			# cls._instance = super(MyTest, cls).__new__(cls, *args, **kwargs)
		return cls._instance

a = MyTest()
b = MyTest()
print a == b

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/796145.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存