后面的代码行似乎会影响前面代码行的执行方式。发生什么事?

2024-06-06 14:28:01 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码块按预期工作

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工作原理的理解,因为我认为后面的行不会影响前面的行的执行方式。我误解了什么,使我无法理解为什么这样执行?如何更改此代码以获得所需的行为?(两个不同的日志条目,取决于它是附加到患者日志还是全部患者日志)


Tags: the代码log患者idattributeallargument
1条回答
网友
1楼 · 发布于 2024-06-06 14:28:01

线路

patient.log.append(entry)

entry字典附加到patient.log,它不会将entry字典的元素“添加”到列表中。所以当你在下一个电话里

entry["patient_id"] = patient.id

您正在更改entry词典,由于patient.log正在引用该词典,因此当您查找该列表时,它将具有更新的信息

解决此问题的一种方法是创建字典的copy,而不是引用,另请参见this post

patient.log.append(entry.copy())

正如那篇文章也提到的,请确保您了解copy是如何工作的,因为它可能并不总是按预期工作。尤其是当复制的对象中存在引用时

相关问题 更多 >