首页 > 解决方案 > 在引用原始变量后编辑它

问题描述

check1 = False
check2 = False

if x == y:
    sending = check1
elif x == z:
    sending = check2

if something is True:
    if sending is False: #actually checks if check1 or check2 is False
        do_stuff()
        sending = True #1 - want to change the actual variable ( check1 or check2 )
        await ask_for_confirmation()
    else:
        return

我参考check1check2依赖于其他一些变量,之后如果选择的变量是Falseido_stuff()ask_for_confirmation(),并且想要将特定选择的变量更改为True它不会do_stuff()再次(确认再次运行整个事情)。

我知道我可以像这样再次检查变量:

check1 = False
check2 = False

if x == y:
    sending = check1
elif x == z:
    sending = check2

if something is True:
    if sending is False:
        do_stuff()
        if x == y:
            check1 = True
        elif x == z:
            check2 = True
        await ask_for_confirmation()
    else:
        return

但这似乎有很多不必要的代码,我觉得有更好的方法来做到这一点。有没有办法可以用参考改变原始变量?(见上面代码中的#1)

标签: python

解决方案


您遇到的问题是,当您重新分配时sending,您只是将其指向不同的值,而不是修改它先前指向的值。

您要做的是将您的两个check值放入一个可变容器中,例如一个列表,然后修改该列表。

checks = [False, False]

if x == y:
    sending = 0
elif x == z:
    sending = 1
# else:
#     sending = ???

if something:
    if checks[sending]:
        return
    do_stuff()
    checks[sending] = True
    await ask_for_confirmation()

或将每个放入自己的可变容器中(您仍然需要为容器下标以访问或修改它包含的值):

check1 = [False]
check2 = [False]

if x == y:
    sending = check1
elif x == z:
    sending = check2
# else:
#     sending = ???

if something:
    if sending[0]:
        return
    do_stuff()
    sending[0] = True
    await ask_for_confirmation()

推荐阅读