SoFunction
Updated on 2024-11-17

Detailed explanation of Python function variable parameter definitions and their parameter passing methods

Python function variable parameter definition and its parameter passing method details

In python, a function with an indefinite parameter is defined as follows

1、 func(*args) 

The incoming arguments are in args in the form of tuples, e.g.:

def func(*args): 
  print args 
 
>>> func(1,2,3) 
(1, 2, 3) 
 
>>> func(*[1,2,3])  # This way you can directly treat all the elements of a list as indeterminate arguments
transmitted inwards(1, 2, 3) 

2、func( **kwargs)

The incoming arguments are in args in dictionary form, e.g.:

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})   # This way you can directly pass all key-value pairs of a dictionary as keyword arguments to the
{'a': 1, 'c': 3, 'b': 2} 

3, you can also mix the two func(*args, **kwargs)

The order of passing in must be the same as the order of definition, in this case an indefinite parameter list followed by a dictionary of keyword parameters, for example:

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> 
 # It's not okay to jump around like this
>>> func(1,2,3, a=4, b=5, c=6, 7) 
SyntaxError: non-keyword arg after keyword arg 

If you have any questions, please leave a message or go to this site community exchange and discussion, thank you for reading, I hope to help everyone, thank you for your support of this site!