I am just writing some dummy code for pygame.
The first sample of code has a function in the menus.py file. I wanted to practice using import. This works fine. I then wanted to put the function in a class so I can get up and running with classes. This is the second block of code. Unfortunately the second block of code doesn't run. Could someone explain where I am going wrong please.
# menus.py
def color_switcher(counter, screen):
black = ( 0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
colors = [black, white, green, red]
screen.fill(colors[counter])
# game.py
#stuff
if event.type == pygame.MOUSEBUTTONDOWN:
menus.color_switcher(counter, screen)
#more stuff
This works fine.
This doesn't
# menus.py
class Menu:
def color_switcher(self, counter, screen):
black = ( 0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
colors = [black, white, green, red]
screen.fill(colors[counter])
# game.py
#stuff
if event.type == pygame.MOUSEBUTTONDOWN:
menus.Menu.color_switcher(counter, screen)
#more stuff
#TypeError: unbound method color_switcher() must be called with Menu instance as first argument (got int instance instead)
Could someone tell me what I am doing wrong with the class please?
class Menu(object):rather thanclass Menu:.staticmethod,classmethodand object instances in general. Also note that in Python if you're not having any instance data---if all your "methods" in the class are just static methods, not needing to useself---you generally shouldn't be using classes. Use functions in a module. They're not bad.(object)bit just makes it a new-style class which makes it behave better in some situations (read about new-style classes for more info). It won't change your problem here, but it's a good habit to get into.