Reputation: 249
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__()'''
I am new to this python.I want to increase the SCORE variable when i call the method from main.py but i am getting error like local variable 'SCORE' referenced before assignment.I know some posts are there with this error but i want to find the solution for this code.
Upvotes: 0
Views: 1075
Reputation: 691
Please add the global
keyword before SCORE
in the function as SCORE
is a global variable. 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.
Change you method as below
def score_change(self):
global SCORE # add this line
SCORE += 1
self.__init__()
Corrected source:
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
Also i would suggest if the SCORE is only used in the context if the Scoreboard Class then you should make it a static member as below and change the def score_change()
method as it was previous. And access the SCORE
how we access static members. like Scoreboard.SCORE
my Suggestion Source:
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)
Upvotes: 1