I am trying to achieve singleton in python. Why is the below code wrong in achieving singleton pattern in Python?
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)
The output:
<__main__.test object at 0x0000023094388400>
Object instantiated
<__main__.test object at 0x00000230949D6700>
Expected Object 'b' to be same as 'a'
Aucun commentaire:
Enregistrer un commentaire