首页 > 解决方案 > 如何防止将变量重新分配给同一类的对象以保留以前的数据?

问题描述

当使用 的新实例重新分配 box 时,它Box不会self.things被分配一个空字典,而是包含来自前一个实例的相同数据。

我正在使用 python 3.7.3

import random

class Box:
    def __init__(self, things = {}):
        self.things = things

    def __str__(self):
        return str(self.things)

    def put_thing_in_location(self, thing, location):
        self.things[location] = thing


for i in range(2):
    box = Box()
    print(box)
    box.put_thing_in_location(
        random.randrange(10000), 
        random.randrange(10000)
    )

输出:

$ python bugTest.py

{}

{652: 8968}

如果没有参数传递给它,我希望它things的新实例是一个空字典。Box相反,它保留thingsBox.

标签: pythonclassdefault-valuekeyword-argument

解决方案


问题是您正在为实例分配与默认字典完全相同的字典,从而在所有实例之间共享它。将您的构造函数更改为

def __init__(self, things=None):
    self.things = {} if things is None else things

这确保了每个实例都将一个新的字典作为默认值,如果没有给出。


推荐阅读