无法通过__init__以外的函数设置self.value

问题描述

我正在pygame中制作平台游戏(只是为了好玩,以学习新概念)。我正在尝试制作滚动背景,当它到达某个点时,我需要重置x值。下面的代码不起作用,pycharm说“该语句似乎无效”。除了__init__以外的其他函数,我不能更改self的值吗?这是我的消息来源:

class background:
    def __init__(self,image_location):
        self.location = pygame.image.load(image_location)

    # defaults V
    class left:
        x = 0 - w/2
        y = 0
    class right:
        x = w/2
        y = 0
    # ^^^^^^^^^^^^^

    def scroll(self):
        if self.left.x > 0-w:
            self.left.x -= 1
        else:
            self.left.x == w
        if self.right.x > 0-w:
            self.right.x -= 1
        else:
            self.right.x == w
        disPLAYSURF.blit(self.location,(self.left.x,self.left.y))
        disPLAYSURF.blit(self.location,(self.right.x,self.right.y))```

解决方法

w未定义,x,y应该是类方法

下面的代码将起作用(假设定义了w)

class left:
    x = 0 - w / 2
    y = 0

class right:
    x = w / 2
    y = 0

class background:
    def __init__(self,image_location):
        self.location = pygame.image.load(image_location)
        self.left = left()
        self.right = right()

    def scroll(self):
        if self.left.x > 0-w:
            self.left.x -= 1
        else:
            self.left.x == w
        if self.right.x > 0-w:
            self.right.x -= 1
        else:
            self.right.x == w
        DISPLAYSURF.blit(self.location,(self.left.x,self.left.y))
        DISPLAYSURF.blit(self.location,(self.right.x,self.right.y))```