在python中更改全局变量的值

时间:2013-12-14 16:50:36

标签: python variables

我需要你的帮助。我已经分配了两个全局变量,我必须在他们的类中更改它们的值,只需看看:

class Lebewesen(object):

    def __init__(self):
        global x
        global y
        x = randint(10, 630)
        y = randint(10, 410)

    def zeichne(self):
        pygame.draw.circle(screen, (225, 30, 0), (x, y), 2)

    def bewege(self):
        x += randint(-1, 2)
        y += randint(-1, 2)

但是当我尝试“bewege”中的部分(德语中的'move')时,我正在分配两个新的局部变量,不是吗?那么如何才能改变全局x和y的值呢?使用返回函数?

3 个答案:

答案 0 :(得分:5)

当你使用global关键字时,你说要使用变量的全局版本(不要将它们设置为全局),所以在init中你正在改变全局变量你想要但是你想要改变局部变量,因为你没有指定你想要使用全局变量。

而是尝试:

def bewege(self):
    global x,y
    x += randint(-1, 2)
    y += randint(-1, 2)

或者(并且更好地练习)使用self来创建对象的变量属性:

class Lebewesen(object):

    def __init__(self):
        self.x = randint(10, 630)
        self.y = randint(10, 410)

    def zeichne(self):
        pygame.draw.circle(screen, (225, 30, 0), (x, y), 2)

    def bewege(self):
        self.x += randint(-1, 2)
        self.y += randint(-1, 2)

然后它们以与定义的方法相同的方式属于该对象。 :)

答案 1 :(得分:1)

您应该xyLebewesen的{​​{3}}:

def __init__(self):
    self.x = randint(10, 630)
    self.y = randint(10, 410)

现在,您可以通过zeichnebewegeself.xself.y访问它们了:

def zeichne(self):
    pygame.draw.circle(screen, (225, 30, 0), (self.x, self.y), 2)

def bewege(self):
    self.x += randint(-1, 2)
    self.y += randint(-1, 2)

答案 2 :(得分:0)

def __init__(self):
    self.x = randint(10, 630)
    self.y = randint(10, 410)
相关问题