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 は、ローカル スコープですべてを実行できるように、使用するすべてのクラス レベル変数を関数に渡す必要がありますか?