I have a class that has a lookup dict in the body of the class in which all instances are stored and with some key.
When I instantiate instances, I do not hold them in any variable or in the external dict, I save them in this lookup dict.
When somehow I create an instance that is already in the dict, I reassign it to the dict file and update it using its new and old value in some other function.
Interestingly, is this a good practice? Or should I refactor and make it have an external dict that contains instances.
Is there any PEP benchmark for this behavior?
Example:
class MyClass:
all_instances = {}
def __init__(self, unique_id, x, y, z):
if unique_id not in MyClass.all_instances:
self.unique_id = unique_id
self.x = x
self.y = y
self.z = z
MyClass.all_instances[unique_id] = self
else:
self = MyClass.all_instances[unique_id]
self.update(x, y, z)
def update(self, new_x, new_y, new_z):
self.x = self.do_something_with(self.x, new_x)
self.y = self.do_something_with(self.y, new_y)
self.z = self.do_something_with(self.z, new_z)
@staticmethod
def do_something_with(old_value, new_value):
value = (old_value + new_value) / 2
return value
while True:
for id in get_ids():
x, y, z = get_values(id)
MyClass(id, x, y, z)
, , , , , , .
, , , , .
, :
class MyClass:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def update(self, new_x, new_y, new_z):
self.x = self.do_something_with(self.x, new_x)
self.y = self.do_something_with(self.y, new_y)
self.z = self.do_something_with(self.z, new_z)
@staticmethod
def do_something_with(old_value, new_value):
value = (old_value + new_value) / 2
return value
all_instances = {}
while True:
for id in get_ids():
x, y, z = get_values(id)
if id not in all_instances:
all_instances[id] = MyClass(x, y, z)
else:
all_instances[id].update(x, y, z)