當python,單例模式,多例模式,一次初始化遇到一起
阿新 • • 發佈:2018-04-15
end light 答案 註意 找到 一次 turn 相關 表示
1.在python中,單例模式是很容易實現的,隨便翻翻網上的相關教程,就能夠找到很多答案。
比如這樣:
class hello(object): def __new__(cls, *args, **kwargs): if not ‘_instance_one‘ in vars(cls): cls._instance_one=object.__new__(cls) return cls._instance_one return cls._instance_one def __init__(self): print self a=hello() b=hello() #************************** result ******************************* <__main__.hello object at 0x7f8afeaf1150> <__main__.hello object at 0x7f8afeaf1150> Process finished with exit code 0
可以看到,兩個實例的內存地址相同,即表示二者是同一個實例 。
註意:如果我們重寫__new__函數的話,需要繼承object類。
2.需要註意到的是 上例中的self和cls._instance_one實際是同一個東西,我們可以簡單做一個測試一下:
class hello(object): def __new__(cls, *args, **kwargs): if not ‘_instance_one‘ in vars(cls): cls._instance_one=object.__new__(cls) print cls._instance_one return cls._instance_one return cls._instance_one def __init__(self): print self a=hello() #************************************** result ********************************** <__main__.hello object at 0x7fb31f65e150> <__main__.hello object at 0x7fb31f65e150> Process finished with exit code 0
3.如果我們需要讓單例模式只初始化一次的話,我們只需要加一個標誌即可:
class hello(object): def __new__(cls, *args, **kwargs): if not ‘_instance_one‘ in vars(cls): cls._instance_one=object.__new__(cls) cls._instance_one._flag=1 return cls._instance_one return cls._instance_one def __init__(self): if self._flag: print self self._flag=0 print "end" a=hello() b=hello() #************************************result********************************* <__main__.hello object at 0x7f14de3bd150> end end
4.註意到上例中的_flag寫在類內,類外都可以,我們同樣可以做一個實驗:
class hello(object): _flag=1 def __new__(cls, *args, **kwargs): if not ‘_instance_one‘ in vars(cls): cls._instance_one=object.__new__(cls) return cls._instance_one if not ‘_instance_two‘ in vars(cls): cls._instance_two=object.__new__(cls) return cls._instance_two def __init__(self): print self._flag self._flag=0 print self._flag a=hello() b=hello() #*************************************result *************************************** 1 0 1 0 Process finished with exit code 0
可以看到二者是等價的。
當python,單例模式,多例模式,一次初始化遇到一起