我想创建一个类,它允许用户创建一个自定义按钮对象,该对象包含按钮的外观属性,以及一个函数,我希望能够在运行时我称这个按钮的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()
这是正确的方式,还是有一种特定的方式来执行这种行动?
红色是否定义?您可能正在寻找“红色”。 – Aereaux
不,我只是用它作为例子,它通常是一个RGB元组。 –