In Python, you can use *args
and **kwargs
to handle an arbitrary number of arguments in a function.
*args
-
Purpose:
- Used to pass an arbitrary number of positional arguments to a function.
*args
receives these arguments as a tuple.
-
Example:
Python
def sum_all(*args):
"""
This function calculates the sum of all the arguments passed to it.
"""
total = 0
for num in args:
total += num
return total
result = sum_all(1, 2, 3, 4, 5)
print(result) # Output: 15
**kwargs
-
Purpose:
- Used to pass an arbitrary number of keyword arguments to a function.
**kwargs
receives these arguments as a dictionary.
-
Example:
Python
def print_info(**kwargs):
"""
This function prints the key-value pairs passed as arguments.
"""
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
Key Points:
- You can use
*args
and**kwargs
together in a function definition. *args
should generally come before**kwargs
in the function definition.- You can use any variable name instead of
*args
and**kwargs
, but these are common conventions.
Benefits of using *args
and **kwargs
:
- Flexibility: Allows you to create functions that can handle a variable number of arguments.
- Reusability: Makes your functions more adaptable and reusable in different situations.
- Improved code readability: Can make your code more concise and easier to understand.
I hope this explanation is helpful!
0 件のコメント:
コメントを投稿