![](/img/trans.png)
[英]Why does the c_score variable and p_score variable increase unstoppably when it should just increase by one in score?
[英]How should i increase the score variable in my python code?
from turtle import Turtle
SCORE=0
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.up()
self.hideturtle()
self.goto(-10,290)
self.write(f"score : {SCORE} ",align="center",font=("Arial",16,"normal"))
def score_change(self):
SCORE+=1
self.__init__()'''
我是這個 python 的新手。當我從 main.py 調用該方法時,我想增加 SCORE 變量,但我收到錯誤,例如在分配之前引用的局部變量“SCORE”。我知道有些帖子有這個錯誤,但我想要找到此代碼的解決方案。
請在 function 的SCORE
之前添加global
關鍵字,因為SCORE
是一個全局變量。 So when you do SCORE += 1
then SCORE
is not found as in python you need to explicitly tell global
to access variables not encapsulated in class else they are interpreted as static members of class as in your case.
改變你的方法如下
def score_change(self):
global SCORE # add this line
SCORE += 1
self.__init__()
更正來源:
from turtle import Turtle
SCORE = 0
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.up()
self.hideturtle()
self.goto(-10,290)
self.write(f"score : {SCORE} ",align="center",font=("Arial",16,"normal"))
def score_change(self):
global SCORE
SCORE += 1
self.__init__()
if __name__ == '__main__':
src = Scoreboard()
src.score_change()
src.score_change()
src.score_change()
print(SCORE)
# Output:
3
另外,我建議如果 SCORE 僅在記分板 Class 的上下文中使用,那么您應該將其設為 static 成員,如下所示,並像以前一樣更改def score_change()
方法。 並訪問我們如何訪問 static 成員的SCORE
。 像Scoreboard.SCORE
我的建議來源:
from turtle import Turtle
class Scoreboard(Turtle):
SCORE = 0
def __init__(self):
super().__init__()
self.color("white")
self.up()
self.hideturtle()
self.goto(-10,290)
self.write(f"score : {Scoreboard.SCORE} ",align="center",font=("Arial",16,"normal"))
def score_change(self):
Scoreboard.SCORE += 1
self.__init__()
if __name__ == '__main__':
src = Scoreboard()
src.score_change()
src.score_change()
src.score_change()
src.score_change()
src.score_change()
print(Scoreboard.SCORE)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.