Passing Functions with Arguments to Another Function in Python
Problem:
Is it feasible to pass functions with arguments to another function in Python? For instance, we want to have a function called perform that accepts other functions as arguments. These passed functions can have varying numbers of parameters, such as action1(), action2(p), and action3(p,r).
Solution:
Yes, it is possible in Python using variable-length argument lists (*args). Here's how you can achieve this:
<code class="python">def perform(fun, *args): fun(*args) def action1(args): # Code for action1 def action2(args): # Code for action2 def action3(args, r): # Code for action3 perform(action1) # No arguments perform(action2, p) # One argument perform(action3, p, r) # Two arguments</code>
In this example, the perform function takes a function fun and arbitrary number of positional arguments *args. It then calls the passed function fun with the provided arguments.
By using *args, you can pass functions with any number of arguments to the perform function. The arguments will be automatically unpacked and passed to the underlying function.
The above is the detailed content of Can Functions with Arguments Be Passed to Other Functions in Python?. For more information, please follow other related articles on the PHP Chinese website!