Reputation: 119
I've been programming in Java for ~2 years, and have just started learning Python(about 1 week in) and PyGame, and have been wanting to create a simple button class, but I don't want the action of the button(what happens when it's pressed) to be hard coded in. What is the best way of doing this in Python/PyGame?
I've also thought of having a variable in the constructor, which is set to a function when it's called, like:
def __init__(self, func)
and called like
act = action()
obj = Button(act)
,
I don't think this will work, but will get back to you all when I test it.
In Java, it would be called like:
button = new Button("Text");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println("ACTION");
}
}
Upvotes: 2
Views: 1166
Reputation: 15847
The only way I know you can pass a function object to another function is by passing its identifier:
# listener function
def listener():
print('listening...')
class Button:
def __init__(self, mouse_listener):
mouse_listener() # you call the function inside __init__
button = Button(listener)
In Python, you can receive a function as parameter because functions are actually objects, but they are special objects, because they can be called or they are callable objects, in fact you could also call explicitly their __call__
default function to invoke a function:
listener.__call__()
but usually you don't do that.
Upvotes: 1