Home >Backend Development >Python Tutorial >How to Pass Functions with Arguments in Python?
Passing Functions with Arguments in Python
In Python, functions can be treated as first-class objects, allowing them to be passed as arguments to other functions. However, when passing functions with arguments, a different approach is required compared to simply passing the function name.
To pass a function with arguments to another function, you can use Python's asterisk operator (*). This operator can be used to collect arbitrary arguments into a tuple.
Here's an example:
<code class="python">def perform(fun, *args): fun(*args) # Define functions with arguments def action1(): # Some action def action2(p): # Some action with parameter 'p' def action3(p, r): # Some action with parameters 'p' and 'r' # Call perform function with different functions and arguments perform(action1) perform(action2, p) perform(action3, p, r)</code>
In this example, the perform function takes two parameters: a function fun and an arbitrary number of arguments denoted by *args. It then calls the passed function fun with the provided arguments using the *args tuple unpacking.
Using this approach, you can pass functions with arguments to other functions in Python, providing greater flexibility and code reusability.
The above is the detailed content of How to Pass Functions with Arguments in Python?. For more information, please follow other related articles on the PHP Chinese website!