Python是支持可变参数的,最简单的方法莫过于使用默认参数,例如:

def test_defargs(one, two = 2):

print 'Required argument: ', one

print 'Optional argument: ', two

test_defargs(1)

# result:

# Required argument: 1

# Optional argument: 2

test_defargs(1, 3)

# result:

# Required argument: 1

# Optional argument: 3

当然,本文章的主题并不是讲默认参数,而是另外一种达到可变参数 (Variable Argument) 的方法:使用*args和**kwargs语法。其中,*args是可变的positional arguments列表,**kwargs是可变的keyword arguments列表。并且,*args必须位于**kwargs之前,因为positional arguments必须位于keyword arguments之前。

首先介绍两者的基本用法。

下面一个例子使用*args,同时包含一个必须的参数:

def test_args(first, *args):

print 'Required argument: ', first

for v in args:

print 'Optional argument: ', v

test_args(1, 2, 3, 4)

# result:

# Required argument: 1

# Optional argument: 2

# Optional argument: 3

# Optional argument: 4

下面一个例子使用*kwargs, 同时包含一个必须的参数和*args列表:

def test_kwargs(first, *args, **kwargs):

print 'Required argument: ', first

for v in args:

print 'Optional argument (*args): ', v

for k, v in kwargs.items():

print 'Optional argument %s (*kwargs): %s' % (k, v)

test_kwargs(1, 2, 3, 4, k1=5, k2=6)

# results:

# Required argument: 1

# Optional argument (*args): 2

# Optional argument (*args): 3

# Optional argument (*args): 4

# Optional argument k2 (*kwargs): 6

# Optional argument k1 (*kwargs): 5

*args和**kwargs语法不仅可以在函数定义中使用,同样可以在函数调用的时候使用。不同的是,如果说在函数定义的位置使用*args和**kwargs是一个将参数pack的过程,那么在函数调用的时候就是一个将参数unpack的过程了。下面使用一个例子来加深理解:

def test_args(first, second, third, fourth, fifth):

print 'First argument: ', first

print 'Second argument: ', second

print 'Third argument: ', third

print 'Fourth argument: ', fourth

print 'Fifth argument: ', fifth

# Use *args

args = [1, 2, 3, 4, 5]

test_args(*args)

# results:

# First argument: 1

# Second argument: 2

# Third argument: 3

# Fourth argument: 4

# Fifth argument: 5

# Use **kwargs

kwargs = {

'first': 1,

'second': 2,

'third': 3,

'fourth': 4,

'fifth': 5

}

test_args(**kwargs)

# results:

# First argument: 1

# Second argument: 2

# Third argument: 3

# Fourth argument: 4

# Fifth argument: 5

使用*args和**kwargs可以非常方便的定义函数,同时可以加强扩展性,以便日后的代码维护。

python的认识_理解 Python 中的 *args 和 **kwargs相关推荐

  1. python生成器用法_理解python中生成器用法

    生成器(generator)概念 生成器不会把结果保存在一个系列中,而是保存生成器的状态,在每次进行迭代时返回一个值,直到遇到StopIteration异常结束. 生成器语法 生成器表达式: 通列表解 ...

  2. python return函数_理解Python函数中的return关键字

    一.说明 return 语句是Python函数返回的结果,可以是数值.字符串.列表.表达式.函数等: return 语句将Python函数的结果,返回到调用的地方,并把程序的控制权一起返回,即在函数中 ...

  3. python全球购代码_理解python的unicode字符串

    基于python2.7中的字符串: unicode-->编码encode('utf-8')-->写入文件 读出文件-->解码decode('utf-8')-->unicode ...

  4. python预定义_【Python】python类中方法的预定义

    知乎问题: 像这个图片里面显示的,self.prediction首先声明了下然后下面给出了定义,然后optimize又调用这个函数但是没有用self.prediction()这样的方式而是像用变量一样 ...

  5. python 概率分布模型_使用python的概率模型进行公司估值

    python 概率分布模型 Note from Towards Data Science's editors: While we allow independent authors to publis ...

  6. Python中的*args和**kwargs是什么?该如何使用?

    2020-01-16 12:30:00 全文共2911字,预计学习时长9分钟 来源:Pexels 在编程中,函数就是生命! 作为使用Python的新手--无论是编程新手,还是熟悉另一语言的人--都需要 ...

  7. python 时间序列预测_使用Python进行动手时间序列预测

    python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...

  8. 一文弄懂Python中的*args 和 **kwargs

    1. 引言 在本文中,我们将讨论 Python 中的 *args 和 **kwargs 及其用法和示例. 闲话少说,我们直接开始吧. 2. 问题引入 在Python中写函数的时候,我们经常需要给函数传 ...

  9. 了解Python中的Args和Kwargs

    在本教程中,我将重点介绍Python中的参数( *args )和关键字参数( *kwargs ). 我将教你什么是args和kwargs,最重要的是,如何使用它们-即如何在函数中接受无限数量的参数和关 ...

最新文章

  1. RuntimeError: Integer division of tensors using div or / is no longer supported, and in a future rel
  2. [转]virtualbox下安装增强工具简单步骤
  3. 【比赛】论如何七天内在研究生电子设计竞赛中拿国奖
  4. 最简单的matplotlib写法
  5. vantUI应用(Tabbar标签页)返回上一页的失效问题
  6. 如何利用计算机英文缩写,【英文缩写】有关计算机的英文都在这儿
  7. Alibaba Druid 源码阅读(五)数据库连接池 连接关闭探索
  8. jsp页面之间传中文参数显示乱码问题的解决
  9. r 语言ylim = c(0 1),今日R--条形图(barplot)
  10. 【高等数学】上册知识点复习
  11. 常用Array对象方法详解(微信小程序)
  12. 在使用firefly的RK3308的SDK使用buildroot构造文件系统时,遇到OEM分区和userdata不能挂在成功的问题
  13. 5 个改善代码可读性的方法
  14. IDEA创建自己的xml类型文件
  15. Word中表的自动断开、且断开处有空白页面的问题之解决
  16. 组建无线网络的六条思路
  17. 华为软件开发云释放莫比嗨客开发潜能
  18. c语言已知红球堆有8个球,c语言 1134.docx
  19. 编程之类的文案_有什么有逼格的四字文案?
  20. Sqli-labs~Less-1~Less-4

热门文章

  1. 投入千亿的菜鸟网络智慧物流做得怎么样?
  2. 研究人员提出增强Wi-Fi传输的新方法
  3. invalidate
  4. DDL、DML、DCL的理解
  5. 纯Shading Language绘制飞机火焰效果
  6. Android底层开发之旅—蓝牙系统分析
  7. oracle索引优劣,ORACLE的五种表的优缺点概述
  8. cas无法使用_并发编程中cas的这三大问题你知道吗?
  9. gridsearchcv参数_使用python进行模型参数调优
  10. window.opener.document.getElementById(“a”)用标准的Jquery 语言怎么写