I am trying to create a class that stores all created instances in the class itself by using new and init magical methods together and I want to return an existing class if it was created before.
My current code looks like this:
class Obj():
_list = []
def __new__(cls, id, *args, **kwargs):
print('new')
for o in Obj._list:
if o.id == id:
print('existent')
return # 'return o' DOES NOT WORK!
instance = super(Obj, cls).__new__(cls, *args, **kwargs)
return instance
def __init__(self, id, *args, **kwargs):
print('init')
super().__init__(*args, **kwargs)
self.id = id
Obj._list.append(self)
Obj(1)
Obj(1)
The code works as it does not produce doubles in the Obj._list (second call of Obj(1) prints 'existent' and cancels the creation of another instance). But when I change the line return
in the new-function to return o
then two instances are created though I want a pointer / the name of the existent instance to be returned and not the creation of another instance.
Any chance to achieve this behaviour with this code or any other solution? I am trying to avoid a function inside the class like:
def get(id):
for i in Obj._list:
if i.id == id:
return i
Obj.get(1).my_method_call()
Any help is appreciated! Many thanks in advance!
Ulrich