我写这篇文章是为了使用 pygame 游戏库创建类似按钮的功能,以学习如何使用 Python。在使用函数 push()
时,我在尝试引用实例变量时收到错误“全局名称 'next' 未定义”。
我不太明白类中的变量是如何工作的,我认为由于使用 self
键盘,环境自动是全局的:它是全局的,因为它是 self< 的成员
。然后其他任何事情都只是在本地范围内。我想这是错误的。那么如何在使用之前定义“全局名称”呢?
按钮:
class Button(object):
def __init__(self,x,y,dimx,dimy,color,phrase):
self.is_clicked = False
self.has_next = False
self.next = None
self.x=x
self.y=y
self.dim_x=dimx
self.dim_y=dimy
self.e_x=x+dimx
self.e_y=y+dimy
self.color=color
self.color2=color
self.phrase=phrase
def mypush(self,btn):
if not (self.has_next):
self.next=btn
self.has_next=True
else:
next.mypush(btn) """ === right here === """
def checkhit(self,x,y):
if ((x>= self.x) or (x<=self.e_x)):
if((y>= self.y) or (y<=self.e_y)):
self.is_clicked = True
self.color = (255,255,255)
return self.phrase
elif (self.has_next == True):
return self.next.checkhit(x,y)
else:
return None
def release(self):
if(self.is_clicked == True):
self.is_clicked=False
self.color=self.color2
elif(self.has_next == True):
self.next.release()
def mydraw(self,the_game,scrn):
the_game.draw.rect(scrn,self.color,[self.x, self.y, self.dim_x,self.dim_y])
if(self.has_next):
self.next.mydraw(the_game,scrn)
...
使用函数推送的地方:
for x in range(2, 10):
btn = Button(10+50*x,470,45,20,(128,64,224),"Button ".join(num[x-1]))
my_button.mypush(btn)
结果:
Traceback (most recent call last):
File "testbutton1.py", line 83, in <module>
my_button.mypush(btn)
File "testbutton1.py", line 22, in mypush
next.mypush(btn)
NameError: global name 'next' is not defined
最佳答案
需要引用成员变量
self.next.mypush(btn)
不是全局变量
next
关于python - 似乎无法引用实例变量,获取 "global name ... is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21594781/