args and kwargs in python
In Python, args and kwargs are special parameters that can be used in function definitions to pass a varying number of arguments to a function.
args is used to pass a variable number of positional arguments to a function. It is a tuple containing all the positional arguments passed to the function. Here's an example:
def my_function(*args):
for arg in args:
print(arg)
my_function('hello', 'world', 123) # prints 'hello', 'world', and 123
In this example, the *args parameter allows the function to accept any number of positional arguments. The for loop then iterates over each argument and prints it.
kwargs is used to pass a variable number of keyword arguments to a function. It is a dictionary containing all the keyword arguments passed to the function. Here's an example:
def my_function(**kwargs):
for key, value in kwargs.items():
print(key, value)
my_function(name='John', age=30, city='New York') # prints 'name John', 'age 30', and 'city New York'
In this example, the **kwargs parameter allows the function to accept any number of keyword arguments. The for loop then iterates over each key-value pair in the dictionary and prints it.
原文地址: https://www.cveoy.top/t/topic/FRD 著作权归作者所有。请勿转载和采集!