如何从模块调用类函数?

1 投票
4 回答
12461 浏览
提问于 2025-04-17 02:51

我正在为pygame写一些简单的代码。

第一段代码是在menus.py文件里有一个函数。我想练习一下如何使用import(导入)。这个是没问题的。然后我想把这个函数放到一个类里,这样我就可以开始学习类的用法了。这是第二段代码。不幸的是,第二段代码没有运行。有人能告诉我我哪里出错了吗?

# 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

这个没问题。

这个不行。

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

有人能告诉我我在类的部分做错了什么吗?

4 个回答

1

你正在尝试把一个实例方法当作类方法来调用。

有两种解决办法:
1) 修改客户端代码:在类的一个实例上调用这个方法

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

2) 修改定义:使用类方法注解把实例方法改成类方法

2

然后我想把这个函数放到一个类里,这样我就可以开始学习类的用法了。

这可不是那么简单。

你真的非常非常需要完成一个完整的Python教程,特别是要学习如何进行面向对象编程。

你很少直接调用一个类的方法。真的很少。

你需要先创建一个类的实例,也就是一个对象,然后再调用这个对象的方法。不是调用类的方法,而是对象的方法。

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

这不是import的问题。因为color_switcher不是静态方法,所以你必须先创建这个类的实例,然后才能调用它的成员函数:

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

另外,你可以把你的类声明为

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

然后你就可以这样使用它:menus.Menu.color_switcher(counter, screen)

撰写回答