[英]Variables defined in a function - Python
I am running this code: https://dpaste.de/RiAP我正在运行此代码: https : //dpaste.de/RiAP
As you see, the variable linespecificpayload
is used only within this function, but if I check the ID, its the same in every function call.如您所见,变量
linespecificpayload
仅在此函数中使用,但如果我检查 ID,它在每个函数调用中都是相同的。
I can't seem to figure out how to flush its value with each call.我似乎无法弄清楚如何在每次调用时刷新其值。 Both the call for
id(linespecificpayload)
return the same value.对
id(linespecificpayload)
的调用都返回相同的值。 Any suggestions would be welcome.欢迎大家提出意见。
Also the code is something I wrote in an hour or two.代码也是我在一两个小时内写的。 So may not be the most efficient one.
所以可能不是最有效的。
The reason is that you are assigning a global object to linespecificpayload
, thus the reference stays the same.原因是您将全局对象分配给
linespecificpayload
,因此引用保持不变。
If you would like to create a copy of the filespecificpayload
dict you can either:如果您想创建
filespecificpayload
dict 的副本,您可以:
use filespecificpayload.copy()
.使用
filespecificpayload.copy()
。 This will create a copy of the dict, but the values that existed before copying will be shared so that id(filespecificpayload[key]) == id(filespecificpayload.copy()[key])
这将创建字典的副本,但复制之前存在的值将被共享,以便
id(filespecificpayload[key]) == id(filespecificpayload.copy()[key])
use copy.deepcopy()
:使用
copy.deepcopy()
:
>>> from copy import deepcopy >>> d = deepcopy(filespecificpayload) >>> id(d[key]) == id(filespecificpayload[key]) False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.