How to use *args and **kwargs in Python
来源:互联网 发布:python lxml 中文教程 编辑:程序博客网 时间:2024/05/16 14:58
This also means how to use variable length argument lists in Python.
The special syntax, *args
and **kwargs
in function definitions is used to pass a variable number of arguments to a function. The single asterisk form (*args
) is used to pass anon-keyworded, variable-length argument list, and the double asterisk form is used to pass akeyworded, variable-length argument list. Here is an example of how to use the non-keyworded form. This example passes one formal (positional) argument, and two more variable length arguments.
def test_var_args(farg, *args): print "formal arg:", farg for arg in args: print "another arg:", argtest_var_args(1, "two", 3)
Results:
formal arg: 1another arg: twoanother arg: 3
Here is an example of how to use the keyworded form. Again, one formal argument and two keyworded variable arguments are passed.
def test_var_kwargs(farg, **kwargs): print "formal arg:", farg for key in kwargs: print "another keyword arg: %s: %s" % (key, kwargs[key])test_var_kwargs(farg=1, myarg2="two", myarg3=3)
Results:
formal arg: 1another keyword arg: myarg2: twoanother keyword arg: myarg3: 3
Using *args
and **kwargs
when calling a function
This special syntax can be used, not only in function definitions, but also whencalling a function.
def test_var_args_call(arg1, arg2, arg3): print "arg1:", arg1 print "arg2:", arg2 print "arg3:", arg3args = (1, "two", 3)test_var_args_call(*args)
Results:
arg1: 1arg2: twoarg3: 3
Here is an example using the keyworded form when calling a function:
def test_var_args_call(arg1, arg2, arg3): print "arg1:", arg1 print "arg2:", arg2 print "arg3:", arg3kwargs = {"arg3": 3, "arg2": "two", "arg1": 1}test_var_args_call(**kwargs)
Results:
See also (updated 2009-04-12):arg1: 1arg2: twoarg3: 3
- Section 4.7More on Defining Functions in theOfficial Python Tutorial
- PEP 3102 Keyword-Only Arguments
- Section 5.3.4Calls in thePython Reference Manual
- How to use *args and **kwargs in Python
- How to use *args and **kwargs in Python
- 如何在python中使用*args,**kwargs (How to use *args and **kwargs in Python)
- python *args and * kwargs
- python *args and **kwargs
- 【python】*args and **kwargs
- 理解python中的 *args??? and **kwargs???
- How to use FTP in Python
- How to use UTF-8 in Python
- How to use urllib2 in Python
- How to use SET in python
- how to use pandas in python
- Python *args 和 **kwargs
- 【python】args kwargs 用法
- python *args和**kwargs
- python *args **kwargs
- python *args **kwargs
- 【PYTHON】*args **kwargs
- 正则表达式30分钟入门教程
- c# 编程 简单实现11个数中选择不重复出现的5个数。
- 单次自动对焦(ONE SHOT)、人工智能自动对焦(AI FOCUS)、人工智能伺服自动对焦(AI SERVO)的区别
- 学生下载 绝对正版
- LINUX常用的基本命令
- How to use *args and **kwargs in Python
- -bash: ./xxx.sh: /bin/sh^M: bad interpreter: 没有那个文件或目录
- C#打印
- Office 2003 出现异常提示遇到问题需要关闭“ 发送错误报告 ”“ 不发送 ”“以安全模式启动”
- linux 自动执行 crontab学习笔记
- BT协议
- javascript打印、设置、预览
- C语言中strcpy,strcmp,strlen,strcat函数原型 .
- xml的相关字符