I am using the following solution to maintain a list of classes instances: https://stackoverflow.com/a/12102163
Now I want to use that list to make sure that there is always only one instance of the class. Renewed initializations of the class should return the one existing instance.
The code I have is:
class MyClass:
instances = []
def __init__(self):
if not MyClass.instances:
self.data=1234
else:
self = MyClass.instances[0]
So:
>> a=MyClass()
>> a.data
1234
And b=MyClass() should return the same instance as a. This is not working. What is wrong with my code?
EDIT: OK, so it turns out I am looking for the singleton pattern, but couldn't recreate it myself. Can anyone please explain why my code does not work?