python - 如何防止将变量重新分配给同一类的对象以保留以前的数据?
问题描述
当使用 的新实例重新分配 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
相反,它保留things
了Box
.
解决方案
问题是您正在为实例分配与默认字典完全相同的字典,从而在所有实例之间共享它。将您的构造函数更改为
def __init__(self, things=None):
self.things = {} if things is None else things
这确保了每个实例都将一个新的字典作为默认值,如果没有给出。
推荐阅读
- vue.js - 为什么不更改 prop 时会触发 Vue.js 中的 watch 方法?
- flutter - 在 Flutter 中,我可以只使用一个控制器从多个 TextField 中检索值吗?
- python - 匹配文件中的空行
- java - jira com.atlassian.jira.issue.link.RemoteIssueLinkBuilder 需要哪个依赖项?
- iis - 在IIS中,如何将cshtml添加到没有扩展名的链接中并进行测试?
- git - Visual Studio - 发布到 Git Hub - 用户取消认证检查
- r - 如何根据频率将 colnames 转换为文本/向量?
- python - 有没有办法不更新 pygame 帧什么都没有发生?
- android - 将手机升级到 Android 9 Pie API 28 修订版 6 后 Cordova 应用程序中出现 Ajax 错误
- python - 如何在我的情节标题中包含多个变量?