全局变量的条件覆盖,本地不可用

时间:2013-09-07 20:11:49

标签: python-3.x global-variables override conditional

为什么这不可能?

CONSTANT = 1
def main():
    if False:
        CONSTANT = 0
    print(CONSTANT)
main()

错误:

UnboundLocalError: local variable 'CONSTANT' referenced before assignment

显式赋值不会改变任何内容:

CONSTANT = 1
def main():
    CONSTANT = CONSTANT
    if False:
        CONSTANT = 0
    print(CONSTANT)
main()

只更改名称才能完成工作:

CONSTANT = 1
def main():
    constant = CONSTANT
    if False:
        constant = 0
    print(constant)
main()

这有点烦人,我可以以某种方式避免这种行为吗?

1 个答案:

答案 0 :(得分:2)

CONSTANT定义为全局。

CONSTANT = 1
def main():
    global CONSTANT
    print(CONSTANT)
    CONSTANT = 0
    print(CONSTANT)
main()