[英]Achieving singleton pattern in python using only __init__ and not using __new__
我試圖在 python 中實現 singleton。為什么下面的代碼在 Python 中實現 singleton 模式是錯誤的?
class test:
_instance = []
def __init__(self):
if len(test._instance)!=0:
print('Object instantiated')
self = test._instance[0]
else:
test._instance.append(self)
a = test()
print(a)
b = test()
print(b)
output:
<__main__.test object at 0x0000023094388400>
Object instantiated
<__main__.test object at 0x00000230949D6700>
Expected Object 'b' to be same as 'a'
對 self 的賦值會將局部變量 self 重新綁定到新的 object。對裸名的賦值不會改變任何 object,它會重新綁定左側的名稱以指向右側的 object。
您可以創建一個 static 方法來管理實例。 我不認為只有__init__
才有可能。
class Test():
obj = None
def __init__(self):
print("__init__")
def GetSingleton():
if Test.obj is None:
Test.obj = Test()
return Test.obj
a = Test.GetSingleton()
b = Test.GetSingleton()
print(a)
print(b)
output
__init__
<__main__.Test object at 0x7f94558b9390>
<__main__.Test object at 0x7f94558b9390>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.