我需要你的帮助.我已经分配了两个全局变量,我必须在他们的类中更改它们的值,只需看看:
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)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试"bewege"中的部分(德语中的'move')时,我正在分配两个新的局部变量,不是吗?那么如何才能改变全局x和y的值呢?有返回功能?
当你使用global关键字时,你说你想要使用变量的全局版本(不要将它们设置为全局),所以在你的init中你正在改变你想要的全局变量,但是在你的抱怨中你正在改变您未指定要使用全局变量的局部变量.
而是尝试:
def bewege(self):
global x,y
x += randint(-1, 2)
y += randint(-1, 2)
Run Code Online (Sandbox Code Playgroud)
或者(并且更好地练习)使用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)
Run Code Online (Sandbox Code Playgroud)
然后它们以与定义的方法相同的方式属于该对象.:)