Python函数参数的传递
2015-04-01 16:06
162 查看
Python函数参数与命令行参数ython中函数参数的传递是通过赋值来传递的。python中函数参数的定义主要有四种方式:
1.F(arg1,arg2,...)
函数调用时必须与括号内参数个数相同,且顺序相同。
2.F(arg1,arg2=value,...)
改函数调用提供了默认值
输出结果为:
1 2
1 3
1 5
3.F(*arg1)
*加上形参名来表示这个函数的实参个数不定,可能为0个也可能为n个。在函数内部都被存放在以形参名为标识符的tuple中。
<class 'tuple'>
(1, 2)
4.F(**arg1)
形参名前加俩个*表示,参数在函数内部将被存放在以形式名为标识符的dictionary中,这时调用函数的方法则需要采用arg1=value1,arg2=value2这样的形式。
输出结果为:
<class 'dict'>
{'x': 1, 'y': 2}
python函数四种定义方式,在调用过程中是如何被解析的
输出结果为:
1 2 () {}
1 2 () {}
1 2 (3, 4, 5) {}
1 2 (3, 4) {'c': 5, 'd': 6}
1 2 () {'c': 5, 'd': 6}
四种方法优先级依次降低1,2,3,4。
1.F(arg1,arg2,...)
函数调用时必须与括号内参数个数相同,且顺序相同。
def fun(x,y): print(x,y) fun(1,2)调用该函数,fun(1,2)则x取1,y取2,fun(1)或者fun(1,2,3)则会报错。
2.F(arg1,arg2=value,...)
改函数调用提供了默认值
def fun(x,y=2): print(x,y) fun(1) fun(1,3) fun(y=5,x=1)
输出结果为:
1 2
1 3
1 5
3.F(*arg1)
*加上形参名来表示这个函数的实参个数不定,可能为0个也可能为n个。在函数内部都被存放在以形参名为标识符的tuple中。
def fun(*arg): print(type(arg)) print(arg) fun(1,2)输出结果为:
<class 'tuple'>
(1, 2)
4.F(**arg1)
形参名前加俩个*表示,参数在函数内部将被存放在以形式名为标识符的dictionary中,这时调用函数的方法则需要采用arg1=value1,arg2=value2这样的形式。
def fun(**arg): print(type(arg)) print(arg) fun(x=1,y=2)
输出结果为:
<class 'dict'>
{'x': 1, 'y': 2}
python函数四种定义方式,在调用过程中是如何被解析的
def fun(x,y,*a,**b): print(x,y,a,b) fun(1,2) fun(x=1,y=2) fun(1,2,3,4,5) fun(1,2,3,4,c=5,d=6) fun(1,2,c=5,d=6)
输出结果为:
1 2 () {}
1 2 () {}
1 2 (3, 4, 5) {}
1 2 (3, 4) {'c': 5, 'd': 6}
1 2 () {'c': 5, 'd': 6}
四种方法优先级依次降低1,2,3,4。
相关文章推荐
- python 函数调用时传递参数的一些规范
- Python中函数的参数传递与可变长参数
- python入门笔记--函数中参数传递
- Python成长之路(三)——词典、文本文件的输入输出、模块、函数的参数传递
- Python引用、浅拷贝、深拷贝 和 Numpy中的视图、副本 和 Python函数参数传递
- python中的函数参数传递
- <Python进阶读书笔记>之(一) 函数不定参数传递
- Python def函数的定义、使用及参数传递实现代码
- Python的函数参数传递:传值?引用?
- python函数参数按引用传递
- python 函数参数的传递(参数带星号的说明)及调用
- python中函数参数的传递
- Python中函数的参数传递与可变长参数
- Python之道–函数参数的传递
- Python的函数参数传递:传值?引用?
- Python函数可变参数定义及其参数传递方式实例详解
- python之函数参数传递
- [蟒蛇菜谱]Python函数参数传递最佳实践
- C与Python函数参数传递总结
- python的函数调用参数传递