从模块调用类函数?

2024-05-31 23:25:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在为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)

有人能告诉我我在课堂上做错了什么吗?


Tags: 代码pycountergreenredscreenpygamecolor
3条回答

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

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

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

2)更改定义:使用class method annotation将实例方法更改为类方法

这不是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)

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

不是那么简单。

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

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

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

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

相关问题 更多 >