2015-05-29 175 views
1

我想创建一个类,它允许用户创建一个自定义按钮对象,该对象包含按钮的外观属性,以及一个函数,我希望能够在运行时我称这个按钮的executeFunction()命令。Python将函数传递给对象

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() 

这是正确的方式,还是有一种特定的方式来执行这种行动?

+0

红色是否定义?您可能正在寻找“红色”。 – Aereaux

+0

不,我只是用它作为例子,它通常是一个RGB元组。 –

回答

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() 
2

你应该有

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

这通过FOO,而不是传递foo的返回值,因为你的代码一样。

+0

因此,如果我传入一个这样的函数,我应该可以从一个方法调用它完全罚款吗? –

+0

@AndrewLalis:是的。 – Aereaux