Python函数可变参数定义及其参数传递方式实例详解

WBOY
Release: 2016-06-06 11:17:55
Original
1608 people have browsed it

本文实例讲述了Python函数可变参数定义及其参数传递方式。分享给大家供大家参考。具体分析如下:

python中 函数不定参数的定义形式如下:

1、func(*args)

传入的参数为以元组形式存在args中,如:

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)

传入的参数为以字典形式存在args中,如:

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、也可以两者混用

func(*args, **kwargs)

传入的顺序必须和定义顺序相同,这里是先不定参数列表,再是关键字参数字典,如:

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

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!