开发者

Calling class function from module?

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_switc开发者_JAVA技巧her(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?


That is not problem with import. Since color_switcher is not static method, you must first create class instance, and only then call a member function:

if event.type == pygame.MOUSEBUTTONDOWN:
     menus.Menu().color_switcher(counter, screen)

Alternatively, you can declare your class as

class Menu:
    @staticmethod
    def color_switcher(counter, screen):

and then use it as menus.Menu.color_switcher(counter, screen)


I then wanted to put the function in a class so I can get up and running with classes

It's not that simple.

You really, really, really need to do a complete Python tutorial that shows how to do object-oriented programming.

You rarely call a method of a class. Rarely.

You create an instance of a class -- an object -- and call methods of the object. Not the class. The object.

x = Menu()
x.color_switcher(counter, screen)


You're trying to call an instance method as a class method.

Two solutions:
1) change the client code: call the method on an instance of the class

menus.Menu().color_switcher(counter, screen) # note the parentheses after Menu

2) change the definition: change the instance method to a class method using the class method annotation


You need to create an instance of Menu before you can call the method. For example:

my_menu = Menu()
my_menu.color_switcher(counter, screen)

You are currently treating color_switcher as if it is a class method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜