【问题标题】:How should i increase the score variable in my python code?我应该如何增加我的 python 代码中的分数变量?
【发布时间】:2021-04-16 04:11:23
【问题描述】:
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'。我知道有些帖子有这个错误但我想找到这段代码的解决方案。

【问题讨论】:

    标签: python python-3.x oop variables compiler-errors


    【解决方案1】:

    请在函数中SCORE 之前添加global 关键字,因为SCORE 是一个全局变量。因此,当您执行SCORE += 1 时,没有像在python 中那样找到SCORE,您需要明确告诉global 访问class 中的未封装的变量,否则它们会被解释作为类的静态成员,就像你的情况一样。

    改变你的方法如下

    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 仅在记分板类的上下文中使用,那么您应该将其设为静态成员,如下所示,并像以前一样更改 def score_change() 方法。并访问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)
    
    

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 2014-01-23
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多