【发布时间】:2020-03-10 11:40:58
【问题描述】:
我正在使用 Python 2.7,我想使用一些东西作为 Javascript 扩展运算符。
我有以下代码:
def some_function():
return {
'a': "test",
'b': 1,
'c': 2
}
mapper = some_function()
test = mapper.update({'a': "Updated"})
print(test)
我想要的结果是:
{
'a': "Updated",
'b': 1,
'c': 2
}
但我得到的是None。
有什么想法吗?
【问题讨论】:
-
测试映射到mapper.update的返回。尝试打印(映射器)而不是
-
mapper现已更新,请参阅print(mapper)。你是说你想让test更新a而不更改mapper? -
@deceze 是的,这就是我想要的。
-
Python 中的一般设计规则是:如果一个函数对一个已经存在的对象进行操作,则该对象将不会被返回。这称为就地操作。
-
他们 python 文档是你的朋友docs.python.org/2/library/stdtypes.html#dict.update 它告诉
Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.所以它会更新你给它的对象,它不会返回更新。
标签: python python-2.7