简体   繁体   English

在函数中定义的变量 - Python

[英]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.

相关问题 访问 Python 函数中定义的变量 - Access variables defined in a function in Python Python:在函数中减去2个已定义的变量 - Python: subtracting 2 already defined variables in a function 自定义 python 函数将无法识别定义的变量 - Custom python function will not recognize defined variables 全局变量的错误未在python上的线程函数中定义 - Error with global variables are not defined in a thread function on python Python:访问函数中定义的未返回的变量 - Python: Accessing variables defined within a function that are not returned 为什么我可以访问在 Python 中的 function 之外有条件定义的变量? - Why can I access variables that are conditionally defined outside of function in Python? 如何获取python中function中定义的所有局部变量? - How to get all the local variables defined inside the function in python? Python 全局变量 - 未定义? - Python Global Variables - Not Defined? python中缺乏一致性,函数前定义变量的行为完全矛盾 - Lack of consistency in python, completely contradictory behaviour of defined variables before function 如何返回在python函数中定义和启动的多个变量? - How can you return multiple variables defined and initiated in a function in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM