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