Home > Article > Backend Development > Analysis of variable parameter definition methods and parameter transfer methods in Python functions
This article mainly introduces relevant information that explains the definition of variable parameters of Python functions and their parameter transfer methods. Here is an example code to help you learn and understand this part of the content. Friends in need can refer to it
Detailed explanation of Python function variable parameter definition and parameter transfer method
The definition form of function variable parameters in python is as follows
1, func(*args )
The parameters passed in are stored in args in the form of tuples, such as:
def func(*args): print args >>> func(1,2,3) (1, 2, 3) >>> func(*[1,2,3]) #这个方式可以直接将一个列表的所有元素当作不定参数 传入(1, 2, 3)
2. func( **kwargs)
The parameters passed in are stored in args in the form of a dictionary, such as:
def func(**kwargs): print kwargs >>> func(a = 1,b = 2, c = 3) {'a': 1, 'c': 3, 'b': 2} >>> func(**{'a':1, 'b':2, 'c':3}) #这个方式可以直接将一个字典的所有键值对当作关键字参数传入 {'a': 1, 'c': 3, 'b': 2}
3. You can also mix the two using func(*args, **kwargs)
The order passed in must be the same as the order of definition. Here is the parameter list. , then the keyword parameter dictionary, such as:
def func(*args, **kwargs): print args print kwargs >>> func(1,2,3) (1, 2, 3) {} >>> func(*[1,2,3]) (1, 2, 3) {} >>> func(a = 1, b = 2, c = 3) () {'a': 1, 'c': 3, 'b': 2} >>> func(**{'a':1, 'b':2, 'c':3}) () {'a': 1, 'c': 3, 'b': 2} >>> func(1,2,3, a = 4, b=5, c=6) (1, 2, 3) {'a': 4, 'c': 6, 'b': 5}</span> #这样跳跃传递是不行的 >>> func(1,2,3, a=4, b=5, c=6, 7) SyntaxError: non-keyword arg after keyword arg
The above is the detailed content of Analysis of variable parameter definition methods and parameter transfer methods in Python functions. For more information, please follow other related articles on the PHP Chinese website!