我想創建一個類,它允許用戶創建一個自定義按鈕對象,該對象包含按鈕的外觀屬性,以及一個函數,我希望能夠在運行時我稱這個按鈕的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元組。 –