player_health = 10
def add(num):
return num + player_health
def monster_room():
print(player_health) # Error on this line
player_health -= 1 # Doesn't crash without this line, even though the error is thrown on the previous line.
print(add(6)) # works
monster_room() # doesn't work
如果我尝试修改,我会收到错误player_health
:
UnboundLocalError:在 main.py 的第 10 行赋值之前引用了局部变量“player_health”
当我可以在add
函数中使用它时,如何可能没有分配变量?它是否因为我试图在函数内部修改它而无法识别它是一个类级变量?Python 是否必须将您要使用的每个类级变量传递给函数,以便它可以在本地范围内执行所有操作?