Python 如何将函数传递并存储到对象中,然后用方法调用?

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

我试图创建一个button类,它将有一个press方法,但是当创建对象时,我在创建对象时传递的函数会立即返回。是否可以将函数传递到对象中并存储结果以供以后调用

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”
,而不是function
func
。在他的情况下,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