python: how to use/declare variables in a class -


so i'm trying best learn how use python , wrote create button functionality using pygame gaming library. in using function push error of "global name 'next' not defined":

button:

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)     ... 

where function push used:

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) 

result:

jdd:my project me$ python testbutton1.py 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' not defined jdd:my project me$ 

i don't understand how variables in classes work, assume environment automatically global due "self" keyboard: global fact member of "self". , else in local scope. guess that's wrong. how define "global name" before used?

you need refer member variable

self.next.mypush(btn) 

not global variable

next 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -