[英]How to modify multiple global variables in a python function
I have several variables and want to modify them with a single function.我有几个变量,想用一个 function 修改它们。
default strength = 0
default dex = 0
default wis = 0
default cha = 0
default point_pool = 5
I can do something like:我可以做类似的事情:
def inc_strength():
global strength
global point_pool
if strength<5 and point_pool>0:
strength = strength+1
point_pool = point_pool-1
But I don't want to create one for each stat.但我不想为每个统计数据创建一个。 I'd prefer to pass the variable I want to use a param, but am struggling.我更愿意传递我想使用参数的变量,但我很挣扎。 Something like:就像是:
def stat_inc(stat):
global point_pool
if stat<5 and point_pool>0:
stat = stat+1
point_pool = point_pool-1
And call it with:并调用它:
action Function(stat_inc(strength))
You can directly update the globals()
dictionary:您可以直接更新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)
That said, I think modifying global values is rarely needed, so it is better if you can do without it.就是说,我认为很少需要修改全局值,所以最好不要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.