Python将函数传递给Obj

2024-03-29 15:14:11 发布

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

我正在尝试创建一个类,允许用户创建一个自定义按钮对象,该对象包含按钮的外观属性,以及一个函数,我希望在调用按钮的executeFunction()命令时能够运行该函数。你知道吗

def foo():
    print "bar"

class Button(object):

    def __init__(self, name, color, function):
        self.name = name
        self.color = color
        self.function = function

    # I want to be able to run the function by calling this method
    def executeFunction(self):
        self.function()

newButton = Button("Example", red, foo())
newButton.executeFunction()

这是正确的方法,还是有具体的方法来执行这种操作?你知道吗


Tags: to对象方法函数用户nameselffoo
2条回答

在python中,函数也是对象,可以传递。您的代码中有一个小错误,并且有一个简单的方法来简化它。你知道吗

第一个问题是调用函数foo,同时将其传递给Button类。这将把foo()的结果传递给类,而不是函数本身。我们只想传递foo。你知道吗

我们可以做的第二件好事就是将函数赋给一个名为function(或者executeFunction)的实例变量,然后可以通过newButton.function()调用它。你知道吗

def foo():
    print "bar"

class Button(object):

    def __init__(self, name, color, function):
        self.name = name
        self.color = color
        self.function = function


newButton = Button("Example", red, foo)
newButton.function()

你应该有

newButton = Button("Example", red, foo)

它传递foo,而不是像代码那样传递foo的返回值。你知道吗

相关问题 更多 >