2
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 是否必须将您要使用的每个类级变量传递给函数,以便它可以在本地范围内执行所有操作?

4

1 回答 1

1

您需要global player_health在其中进行更改的每个功能中对其进行更改player_health

于 2021-04-13T01:58:02.397 回答