python - 如何在python函数中修改多个全局变量
问题描述
我有几个变量,想用一个函数修改它们。
default strength = 0
default dex = 0
default wis = 0
default cha = 0
default point_pool = 5
我可以做类似的事情:
def inc_strength():
global strength
global point_pool
if strength<5 and point_pool>0:
strength = strength+1
point_pool = point_pool-1
但我不想为每个统计数据创建一个。我更愿意传递我想使用参数的变量,但我很挣扎。就像是:
def stat_inc(stat):
global point_pool
if stat<5 and point_pool>0:
stat = stat+1
point_pool = point_pool-1
并调用它:
action Function(stat_inc(strength))
解决方案
您可以直接更新globals()
字典:
>>> def stat_inc(arg1, arg2):
stat = globals()[arg1]
point_pool = globals()[arg2]
if stat<5 and point_pool>0:
stat = stat+1
point_pool = point_pool-1
globals()[arg1] = stat
globals()[arg2] = point_pool
>>> stat=3
>>> point_pool = 3
>>> stat_inc('stat', 'point_pool')
>>> stat, point_pool
(4, 2)
就是说,我认为很少需要修改全局值,所以最好不要它。
推荐阅读
- php - 查询返回 null 并期望 1
- amazon-web-services - VPC 中的默认安全组
- python - 如何检查某人是否是管理员[Python中的Discord bot]
- dart - Named parameter with underscore in Dart class
- hibernate - Hibernate - 如何在 JSONB 列中保存 Json 字符串
- c - C中局部变量的自动初始化
- android - 正在创建通知但未在 android 中弹出(在 Pie 中)
- c++ - 如何加载带后缀的库
- node.js - 使用 ES7 和 babel 调试 nodejs 代码时 VS 代码中的异常
- ios - 如何快速将文本字段的文本带到渐变背景的前面