python - 如何在python中将函数的位置参数声明为全局变量?
问题描述
如何var
将以下函数中的位置参数声明为全局变量?
v1 = 'a1'
v2 = 'a2'
# and there may be other variables like v3, v4
def test(var):
global var
var += '-new'
test(v1)
print(v1) # I hope this can be a1-new
test(v2)
print(v2) # I hope this can be a2-new
解决方案
您不需要使用全局变量,但如果这样做,请执行如下 for 循环:
var_names = ["v1", "v2"]
for i in var_names:
globals()[i] = f"{i}-new"
要访问新的全局变量,只需键入:globals()["var_name"]
推荐阅读
- c++ - OpenCV QT,显示视频帧(不使用 While 循环)
- vue.js - 如何使用 GitLab 为具有多个 .env 文件的 Vue 应用程序进行单个构建
- reactjs - 在其参数“img”范围之外定义函数 animate() 失败,使用 react useEffect
- python - Python 从第五张幻灯片插入图像
- java - 在 .bash_profile 中设置 JAVA_HOME 和 M2_HOME 时遇到问题 - Amazon Linux EC2
- xamarin - 如果标签为空,如何初始化 Nfc 标签并使其在 Xamarin Android 中受密码保护?
- c# - 错误 - 当我尝试在 .net core 2.2 中启用迁移时,项目中未安装实体框架包
- c# - 如何将带有变量的 onClick 侦听器添加到按钮?
- express - `public` 文件夹中的静态文件未提供服务(使用 ExpressJS 的 NextJS 自定义服务器)
- php - 如何防止 WooCommerce 上的产品被 Google 索引?