为什么这不可能?
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()
这有点烦人,我可以以某种方式避免这种行为吗?
答案 0 :(得分:2)
将CONSTANT
定义为全局。
CONSTANT = 1
def main():
global CONSTANT
print(CONSTANT)
CONSTANT = 0
print(CONSTANT)
main()