0

I'm trying to create a button class that will have a press method, but when the object is created the function that I pass while creating the object is returned immediately. Is it possible to pass functions into objects and store the results to later be called?

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
  • 1
    Briefly: don't call it. – TigerhawkT3 Mar 22 '16 at 22:14
  • You're calling it when you pass it in with `button1 = Button(func())`. Don't call it there. In fact, calling it there will make `button1.function` refer to the string `'results'` rather than the function `func`. – TigerhawkT3 Mar 22 '16 at 22:18
  • well `button1.function` will refer to `None` in his case since he's just printing – Bahrom Mar 22 '16 at 22:20

2 Answers2

0

You want to pass in a function, not the output of that function so you'll need Button(func). Inside press however, you want to call it: return self.function()

Bahrom
  • 4,752
  • 32
  • 41
  • 1
    It's working now thanks. I typed the psuedocode up quickly so I must have missed the typo in press. Thanks for the quick fix though. I would upvote your response but I don't have enough 'reputation' lol. – Anthony Rotiroti Mar 22 '16 at 22:20
  • no worries, good luck :) – Bahrom Mar 22 '16 at 22:23
0

You have to pass the function func not the result of the function func(), then call it in press() with function()

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
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99