我一直收到错误:
UnboundLocalError: local variable 'var' referenced before assignment
当我尝试跑步时
def func1():
var = True
def func2():
if something_random and var == True:
do stuff
答案 0 :(得分:0)
这是因为var
是在func1
的范围内定义的,而不在func2
的范围内。 See this用于解释python中的变量作用域。
答案 1 :(得分:0)
当你在python函数中赋值变量时,默认情况下该变量是函数的本地变量。您可以使其全球化:
var = False # What if func2 was called before func1?
def func1():
global var
var = True
def func2():
global var # Not strictly required, but documentary
something_random = True
if something_random and var == True:
print("stuff")
func1()
func2()
但是应尽可能避免全局变量。为什么?因为在设置它们的地方可能很难,并且这意味着这些功能不能在其他地方重复使用。
因此,更好的解决方案是封装:
def func1():
var = True
return var # func1 could be shortened to: return True
def func2(var):
something_random = True
if something_random and var == True:
print("stuff")
result = func1()
func2(result) # Some people prefer: func2(func1())