python - 将函数作为参数传递

标签 python function arguments

我知道这里有一些非常基本的错误,但我只是看不到。如果在 Python 方面更有经验的人能够指出我在这里误解的地方,我将非常感激。我在下面发布了我的代码的简化版本。要追溯到问题的根源,请注意以下几点:

MainProgram 实例化为 Main = MainProgram(),有一个菜单 (self.menu = Startmenu()),它是Menu 类的实例。这个 Menu 类有一个按钮列表 (self.buttons = [...]) - 在本例中只有一个。它们是 Button 类的实例。我现在需要将单击按钮时要触发的函数传递给 Button 类的该实例,以便我可以实际使用它。

我真的很感谢任何有经验的用户快速浏览一下它。我确信我没有看到一些非常基本的东西。我敢打赌我太累了,看不到它......因为现在家里有婴儿,所以只睡了大约 2 个小时:D

我的代码:

class MainProgram:
    #Much much more code
    def __init__(self):
        #And so much more code here
         self.menu = StartMenu()

class StartMenu:
    def __init__(self):
        #Much code which is not important to us here
        self.buttons = [Button("d_bt_start", (100, 60)
                                       , testfunc, "TEST-TEXT")]

class Button:
    def __init__(self, image, pos = (0, 0), path = Paths.path_img
                 , alpha = False, func = None, args = None):
        self.img_normal = helper.loadImage(path, image + "_normal.jpg", alpha)
        self.img_hover = helper.loadImage(path, image + "_hover.jpg", alpha)

        self.image = self.img_normal

        self.pos = pos

        self.x = pos[0]
        self.y = pos[1]
        self.width = self.x + self.image.get_width()
        self.height = self.y + self.image.get_height()

        self.mouseover = 0

        self.func = func
        self.args = args

    def update(self, (mx, my)):
        if (mx >= self.x and mx <= self.width and
            my >= self.y and my <= self.height):
            if self.mouseover == 0:
                self.image = self.img_hover
                self.mouseover = 1
        else:
            if self.mouseover == 1:
                self.image = self.img_normal
                self.mouseover = 0

    def clicked(self, button):
        if (mx >= self.x and mx <= self.width and
            my >= self.y and my <= self.height):
            if button == 1:
                self.func(self.args)

应该发生什么:主文件创建 StartMenu 类的实例。在 StartMenu 类中,我们将一个按钮定义为 Button 类的实例。单击该按钮后应触发函数 testfunc(args)。到目前为止,这个测试函数只是“TEST-TEXT”参数的打印。

如果我将函数传递为

testfunc

然后我收到以下错误回溯:

Traceback (most recent call last):
  File "D:\Python27\_RPG DEMO\DEMO\main.py", line 41, in <module>
   Main = MainProgram()
  File "D:\Python27\_RPG DEMO\DEMO\main.py", line 21, in __init__
    self.menu = menus.StartMenu()
  File "D:\Python27\_RPG DEMO\DEMO\menus.py", line 11, in __init__
    , zztestfile.testfunc, "TESTEST")
  File "D:\Python27\_RPG DEMO\DEMO\buttons.py", line 7, in __init__
    self.img_normal = helper.loadImage(path, image + "_normal.jpg", alpha)
  File "D:\Python27\_RPG DEMO\DEMO\helper.py", line 13, in loadImage
    return pygame.image.load(os.path.join(folder, name)).convert_alpha()
  File "D:\Python27\lib\ntpath.py", line 96, in join
    assert len(path) > 0
TypeError: object of type 'function' has no len()

如果我将其传递为:

testfunc("TEST-TEXT")

它会触发,但随后会导致以下回溯:

TEST-TEXT

Traceback (most recent call last):
  File "D:\Python27\_RPG DEMO\DEMO\main.py", line 41, in <module>
    Main = MainProgram()
  File "D:\Python27\_RPG DEMO\DEMO\main.py", line 21, in __init__
    self.menu = menus.StartMenu()
  File "D:\Python27\_RPG DEMO\DEMO\menus.py", line 11, in __init__
    , testfunc("TEST-TEXT"))
  File "D:\Python27\_RPG DEMO\DEMO\buttons.py", line 7, in __init__
    self.img_normal = helper.loadImage(path, image + "_normal.jpg", alpha)
  File "D:\Python27\_RPG DEMO\DEMO\helper.py", line 15, in loadImage
    return pygame.image.load(os.path.join(folder, name)).convert()
  File "D:\Python27\lib\ntpath.py", line 96, in join
    assert len(path) > 0
TypeError: object of type 'NoneType' has no len()

到目前为止,我已经阅读了一些教程,但我真的不知道我在哪里误解了它们。我真的很感激任何帮助!

最佳答案

您正在将测试函数传递给 Button 类的 path 参数:

self.buttons = [Button("d_bt_start", (100, 60)
                               , testfunc, "TEST-TEXT")]

这是第三个位置参数:

def __init__(self, image, pos = (0, 0), path = Paths.path_img
             , alpha = False, func = None, args = None):

路径匹配。使用关键字参数代替:

self.buttons = [Button("d_bt_start", (100, 60)
                               , func=testfunc, args="TEST-TEXT")]

关于python - 将函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23106727/

相关文章:

function - 函数的参数太多

python - 使用 Python 将虚拟数据填充到 MySQL 表中

python - 条件 numpy 乘法的矢量化实现

python - PySide/PyQt 覆盖小部件

ios - Swift:声音返回 nil

javascript - 如何使用 javascript 函数使隐藏的 html <div> 可见?

BASH shell 用变量中的空格扩展参数

python - 在 Pandas 数据框中插入缺失的类别和日期

php - 当用户点击显示更多按钮时显示更多帖子

python - 如何读取包含默认参数值的函数签名?