下面的代码块按预期工作
patient = Patient()
patient.log = []
patient.id = "xyz"
patient.example_attribute = []
ALL_PATIENT_LOG = []
def update(patient, attribute, argument, replace = False):
now = datetime.now()
entry = {"argument": argument, "attribute": attribute, "time": now.strftime("%H:%M on %d/%m/%y")}
patient.log.append(entry)
但是当我在更新的末尾添加以下内容时
entry["patient_id"] = patient.id # we also need to include the patient's ID for the global log
ALL_PATIENT_LOG.append(entry)
if replace:
patient.__dict__[attribute] = [argument]
else:
patient.__dict__[attribute].append(argument)
将更改patient.log条目,使其也包含患者id
这违背了我对python工作原理的理解,因为我认为后面的行不会影响前面的行的执行方式。我误解了什么,使我无法理解为什么这样执行?如何更改此代码以获得所需的行为?(两个不同的日志条目,取决于它是附加到患者日志还是全部患者日志)
线路
将
entry
字典附加到patient.log
,它不会将entry
字典的元素“添加”到列表中。所以当你在下一个电话里您正在更改
entry
词典,由于patient.log
正在引用该词典,因此当您查找该列表时,它将具有更新的信息解决此问题的一种方法是创建字典的
copy
,而不是引用,另请参见this post:正如那篇文章也提到的,请确保您了解
copy
是如何工作的,因为它可能并不总是按预期工作。尤其是当复制的对象中存在引用时相关问题 更多 >
编程相关推荐