Pythonでの単例モードの簡単な使用

907 ワード

'''
                     
                 ,               
          ,  __new__              ,                ,
                 ,        ,      ,                ,
  :   ,                   、           
'''
class MyClass(object):
	instance = None

	def __new__(cls, *args, **kwargs):
		if cls.instance:
			return cls.instance

		else:
			cls.instance = super(MyClass, cls).__new__(cls,*args, **kwargs)
			return cls.instance


myclass1 = MyClass()
myclass2 = MyClass()

print(id(myclass1))
print(id(myclass2))


'             ,     '
from functools import wraps


def singleton(cls):
	instances = {}

	@wraps(cls)
	def getinstance(*args, **kwargs):
		if cls not in instances:
			instances[cls] = cls(*args, **kwargs)
		return  instances[cls]
	return getinstance


@singleton
class test(object):
	pass


a = test()
b = test()
print(id(a))
print(id(b))