Python 如何将函数传递并存储到对象中,然后用方法调用?
我试图创建一个button类,它将有一个press方法,但是当创建对象时,我在创建对象时传递的函数会立即返回。是否可以将函数传递到对象中并存储结果以供以后调用Python 如何将函数传递并存储到对象中,然后用方法调用?,python,python-2.7,Python,Python 2.7,我试图创建一个button类,它将有一个press方法,但是当创建对象时,我在创建对象时传递的函数会立即返回。是否可以将函数传递到对象中并存储结果以供以后调用 class Button: def __init__(self, function): self.function = function def press(self): return self.function def func(): print("results") bu
class Button:
def __init__(self, function):
self.function = function
def press(self):
return self.function
def func():
print("results")
button1 = Button(func())
#results is printed here
button1.press()
#I want results to be printed here
您希望传入一个函数,而不是该函数的输出,因此需要
按钮(func)
。在内按
但是,您要调用它:返回self.function()
您必须传递函数func
而不是函数func()
的结果,然后使用function()在press()
中调用它
简单地说:不要调用它。当您使用button1=Button(func())
传递它时,您正在调用它。别在那叫它。事实上,在那里调用它将使按钮1。function
引用字符串“results”
,而不是functionfunc
。在他的情况下,function
将引用None
,因为他刚刚打印,现在正在工作,谢谢。我很快就把密码打出来了,所以我一定错过了印刷机上的打字错误。谢谢你的快速修复。我会支持你的回答,但我没有足够的“声誉”哈哈。别担心,祝你好运:)
class Button:
def __init__(self, function):
self.function = function
def press(self):
return self.function()
def func():
print("results")
button1 = Button(func)
#results is NOT printed here
button1.press()
#results is printed here