Home > Backend Development > Python Tutorial > Analysis of variable parameter definition methods and parameter transfer methods in Python functions

Analysis of variable parameter definition methods and parameter transfer methods in Python functions

巴扎黑
Release: 2017-08-06 16:17:30
Original
1445 people have browsed it

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)
Copy after login

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}
Copy after login

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) 
{&#39;a&#39;: 4, &#39;c&#39;: 6, &#39;b&#39;: 5}</span> 
 #这样跳跃传递是不行的 
>>> func(1,2,3, a=4, b=5, c=6, 7) 
SyntaxError: non-keyword arg after keyword arg
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template