メタクラスによる単一モードの実装

421 ワード

class Singleton(type):
	def __init__(self, *args, **kwargs):
		self._instance = None 
		super(Singleton, self).__init__(*args, **kwargs)

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

class Test(object):
	__metaclass__ = Singleton
	pass 

t1 = Test()
t2 = Test()
print t1 is t2    #True