0

我有几个变量,想用一个函数修改它们。

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))
4

1 回答 1

1

您可以直接更新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)

就是说,我认为很少需要修改全局值,所以最好不要它。

于 2021-01-19T19:55:42.840 回答