[英]Globals lost when function calls itself
I need to add a variable "a" to global variables at runtime and be able to recover it anytime from the Item class.我需要在运行时向全局变量添加一个变量“a”,并且能够随时从 Item 类中恢复它。 Result: I can't see it in the global variables.结果:我在全局变量中看不到它。
Below there is an example.下面有一个例子。 When I print the globals() I don't find the new "a" variable.当我打印 globals() 时,我没有找到新的“a”变量。
Specifically I need to be able to save the printVal result in a variable called "a", which I can consult in next call to this function.具体来说,我需要能够将 printVal 结果保存在一个名为“a”的变量中,我可以在下次调用此函数时查阅该变量。
In my final program I plan to add as many different variables as I want (variable and value).在我的最终程序中,我计划添加任意数量的不同变量(变量和值)。
Example:例子:
class Item():
def printVal(self,value):
return value
def func(self):
userInput = input("Input string:")
if userInput!="0":
exec("a=self.printVal(\""+userInput+"\")",globals(),locals())
else:
return
print(globals())
self.func()
if __name__ == "__main__":
item = Item()
item.func()
If you jus watn to set a global variable with a name generated at runtime you do:如果你只是想用在运行时生成的名称来设置一个全局变量,你可以:
globals()[name] = val
by the way printVal
method is dummy.顺便说一下, printVal
方法是虚拟的。 Just return whtat it gets.只需返回它得到的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.