我有一个类在类体中有查找字典,我存储所有实例和一些键.
当我实例化实例时,我没有在任何变量或外部字典中保存它们,我将它们存储在这个查找字典中.
当我以某种方式实例化一个已经在dict中的实例时,我将它重新分配给dict中的那个并更新它,在其他函数中使用它的新旧值.
我想知道这是一个好习惯吗?或者我应该重构并让它有一个外部字典来保存实例.
这种行为有没有PEP指南?
例:
class MyClass:
all_instances = {} # this dictionary is in local space and it's clear that
# the only interaction is with MyClass
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):
# do something with old value and new and return some value
value = (old_value + new_value) / 2 # more complicated than tht
return value
while True:
for id in get_ids(): # fetch ids from some database
x, y, z = get_values(id) # fetch values from some other database
MyClass(id, x, y, z)
我得到id和值的数据库每次都在变化,所以我无法确定我是否会得到我已经实例化的数据,或者值不同.
我看到的方式是,类的所有功能都在其自身内部发生,不需要使用字典,因此不清楚它们与代码的任何其他部分的交互位置.
这是我通常会做的,没有重新分配它:
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):
# do something with old value and new and return some value
value = (old_value + new_value) / 2 # more complicated than tht
return value
all_instances = {} # this dictionary is now in global space
# and it's unclear if the only interaction is with MyClass
while True:
for id in get_ids(): # fetch ids from some database
x, y, z = get_values(id) # fetch values from some other database
if id not in all_instances:
all_instances[id] = MyClass(x, y, z)
else:
all_instances[id].update(x, y, z)