Python] Python函数参数中的*,** 以及不带*的差异!
来源:互联网 发布:三星移动数据开关 编辑:程序博客网 时间:2024/06/05 12:07
Python的函数定义中有两种特殊的情况,即出现*,**的形式,加上不带*的,三种情况,差异性在哪里呢?
第一种:参数个数固定,可以带参数名字,或者不带名字。
第二种:参数个数任意,但不能带参数名字,参数是tuple类型。
第三种,参数个数任意,但必须带参数名字,参数是dict类型。
看代码:
如:def fun1(arg)或def fun2(arg),def fun3( **arg),等。
def fun1(arg):
print ("arg type=" + str(type(arg)))
print ("arg=" + str(arg))
fun1(2)
fun1(arg=3)
运行结果:
arg type=<class 'int'>
arg=3
arg type=<class 'int'>
arg=2
没有带*参数,但可以使用带参数名称来传递参数,叶不可以不带名字,但参数个数必须一致。
def fun2(*arg):
print ("arg type=" + str(type(arg)))
print ("arg=" + str(arg))
for i in range(0, len(arg)):
print ("arg[" + str(i) + "]=" + str(arg[i]))
fun2(2,3)
fun2()
运行结果:
arg type=<class 'tuple'>
arg=(2, 3)
arg[0]=2
arg[1]=3
arg type=<class 'tuple'>
arg=()
>>>带*的参数,可以任意多的参数,或者无参数,但只能是无名字参数。
def fun3(**arg):
print ("arg type=" + str(type(arg)))
print ("arg=" + str(arg))
print ("age:" + str(arg['age']))
print ("name:" + str(arg['name']))
fun3(age=2,name=3)
fun3(name=2, age=3)
运行结果:
def fun3(**arg):
print ("arg type=" + str(type(arg)))
print ("arg=" + str(arg))
print ("age:" + str(arg['age']))
print ("name:" + str(arg['name']))
fun3(age=2,name=3)
fun3(name=2, age=3)
运行结果:
arg type=<class 'dict'>
arg={'name': 3, 'age': 2}
age:2
name:3
arg type=<class 'dict'>
arg={'name': 2, 'age': 3}
age:3
name:2
arg type=<class 'dict'>
arg={}
>>>带**的参数,可以任意多的参数,或者无参数,但只能是有名字参数。
- Python] Python函数参数中的*,** 以及不带*的差异!
- Python函数带*的参数
- python中的装饰器,函数带参数的装饰器,带类参数的装饰器
- python函数传递带*的参数说明
- Python带星号*的函数参数
- [python]带参数的装饰函数解析
- python的strip('')函数带参数
- python函数参数带星号*
- python函数参数带星号*
- python函数参数带星号*
- python函数参数带星号*
- python函数参数带星号*
- [Python]Python函数参数中的*,**
- python 函数参数的传递(参数带星号的说明)
- python 函数参数的传递(参数带星号的说明)
- python 函数参数的传递(参数带星号的说明)
- python 函数参数的传递(参数带星号的说明)
- python 函数参数的传递(参数带星号的说明)
- oracle 操作数据表结构
- Cocos2d-x下Lua调用自定义C++类和函数的最佳实践
- sort stl
- cocos2dx 导演、场景、层、精灵之間的關係
- Fedora下编译模块驱动
- Python] Python函数参数中的*,** 以及不带*的差异!
- 看了这个才发现jQuery源代码不是那么晦涩
- 稳定排序和不稳定排序
- c#c语言参数对照表
- 破解Xcode 6.1 免证书真机应用测试
- 【转】snprintf函数用法
- 解决chromium对html5 标签的 mp3 等视频音频网页的兼容性问题
- Git和Repo管理使用简要介绍
- alter table *** add constraint *** 用法