微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决无法通过__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))```

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。