![](/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.