我想创建一个函数,该函数将根据传递给它的参数修改一个初始化的全局变量,但是我得到一个 SyntaxError:name'arg'是局部的和全局的.我已经看到了其他方法来实现此目的,可以使用 globals()或在 myFunc 内部创建一个简单的func来欺骗" Python.另一种方法是在 myFunc 内创建if语句以显式分配相应的全局变量,但这似乎太冗长了.
I'd like to create a function that will modify an initialized global variable based on the argument passed to it, but I get a SyntaxError: name 'arg' is local and global. I have seen other methods to accomplish this, using globals() or creating a simple func inside myFunc to "trick" Python. Another approach would be to create if statements inside myFunc to explicitly assign the corresponding global variables, but that seems overly verbose.
为什么会发生这种情况?最有效/优雅/Pythonic的方法是什么?
Why does this occur, and what would be the most efficient/elegant/Pythonic way to accomplish this?
给出:
var1 = 1 var2 = 2 var3 = 3 def myFunc(arg): global arg arg = 10 myFunc(var1) # each of these should print to 10 myFunc(var2) myFunc(var3) 推荐答案您可以使用 globals()访问变量并从 myFunc()中分配新值
You can use globals() to access the variables and assign new values from within myFunc()
var1 = 1 var2 = 2 def myFunc(varname): globals()[varname] = 10 print(var1, var2) myFunc("var1") myFunc("var2") print(var1, var2)将输出:
1, 2 10, 10更多推荐
Python:从函数参数修改全局变量
发布评论