从模块调用类函数?

时间:2011-09-22 13:53:06

标签: python class-method

我正在为pygame编写一些虚拟代码。

第一个代码示例在menus.py文件中有一个函数。我想练习导入。这很好用。然后我想把这个函数放在一个类中,这样我就可以启动并运行类了。这是第二块代码。不幸的是,第二个代码块没有运行。有人可以解释我出错的地方吗。

# 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 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

您正在尝试将实例方法称为类方法。

两种解决方案:
1)更改客户端代码:在类的实例上调用方法

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

2)更改定义:使用class method annotation

将实例方法更改为类方法

答案 2 :(得分:1)

  

然后我想把这个函数放在一个类中,这样我就可以启动并运行类

这不是那么简单。

你真的,真的,真的需要做一个完整的Python教程,展示如何进行面向对象的编程。

你很少调用类的方法。很少。

您创建一个类的实例 - 一个对象 - 并调用该对象的方法。不是班级。对象。

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

答案 3 :(得分:1)

您需要先创建一个Menu实例,然后才能调用该方法。例如:

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

您目前正在将color_switcher视为class method