Python:从函数参数修改全局变量

编程入门 行业动态 更新时间:2024-10-09 06:29:52
本文介绍了Python:从函数参数修改全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想创建一个函数,该函数将根据传递给它的参数修改一个初始化的全局变量,但是我得到一个 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:从函数参数修改全局变量

本文发布于:2023-10-30 18:40:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543684.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   全局变量   参数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!