我只是写了一些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)
有人能告诉我什么,我做错了带班好吗?
注意:如果你使用Python 2,你应该使用'class Menu(object):'而不是'class Menu:'。 –
关于哪些内容可以帮助您:“staticmethod”,“classmethod”和一般对象实例。还要注意,在Python中,如果你没有任何实例数据---如果你在类中的所有“方法”只是静态方法,不需要使用“self”---你通常不应该使用类。使用模块中的功能。他们并不坏。 –
谢谢,我补充说,但错误仍然存在。编辑:我一直在阅读类文档。这就是我得到这个目标的方法,但就我的未经训练的眼睛而言,可以告诉我的代码示例没有太多错误。 – JohnnyFive