2011-09-22 61 views
1

我只是写了一些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) 

有人能告诉我什么,我做错了带班好吗?

+0

注意:如果你使用Python 2,你应该使用'class Menu(object):'而不是'class Menu:'。 –

+2

关于哪些内容可以帮助您:“staticmethod”,“classmethod”和一般对象实例。还要注意,在Python中,如果你没有任何实例数据---如果你在类中的所有“方法”只是静态方法,不需要使用“self”---你通常不应该使用类。使用模块中的功能。他们并不坏。 –

+0

谢谢,我补充说,但错误仍然存​​在。编辑:我一直在阅读类文档。这就是我得到这个目标的方法,但就我的未经训练的眼睛而言,可以告诉我的代码示例没有太多错误。 – JohnnyFive

回答

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)

+0

这是一种方法,而不是函数,你也可以在类上调用类的方法。 – agf

+0

@agf感谢您的纠正,更新了我的答案 – aland

1

您试图调用实例方法作为类方法。

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

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

2)的实例改变定义:使用class method annotation

更改的实例方法的一类方法
1

我当时就想放功能的一类,所以我可以站起来与类运行

并不那么简单。

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

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

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

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

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

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

您正在治疗color_switcher,就好像它是一个class method