函数调用与回调的区别及无参数回调调用方式咨询
Can I call
on_goal() without parameters the regular way when using callback=self.on_goal? Absolutely! Let's break this down based on the two scenarios you're likely working with:
1. When passing a callback reference to another function/method
- When you write
callback=self.on_goal, you're handing over a reference to the function itself to whatever system expects the callback. That system will then invokeon_goal()without arguments at the right time. - If you tried
callback=self.on_goal()instead, this would immediately runon_goal()right then and there, and pass its return value to thecallbackparameter. This is almost never what you want for a callback (unlesson_goalreturns another callable function, which is a more advanced edge case).
2. When you want to directly invoke on_goal() without parameters
- This is totally straightforward! You can call it the regular way anytime:
self.on_goal(). This will execute the function immediately, no callback setup needed.
Quick example to make it concrete:
class Game: def on_goal(self): print("Score!") def register_event(self, trigger_event): # Simulate an event triggering later trigger_event() # Using as a callback my_game = Game() my_game.register_event(trigger_event=my_game.on_goal) # Correct: passes function reference, which gets called later # Regular direct call my_game.on_goal() # Directly executes, prints "Score!"
So to sum up: use self.on_goal when you need to pass the function as a callback (so it can be invoked later), and use self.on_goal() when you want to call it immediately the standard way.
内容的提问来源于stack exchange,提问作者Dave 494
相关产品推荐
相关产品推荐

