函数的参数传递
1. 参数定义与传递的基本顺序
位置参数——>关键字参数——>可变数量参数
- 位置参数
根据位置传递的参数
>>> def add(x,y):
>>> return x + y
>>> add(3,4)
7
- 关键字参数
根据关键字传递的参数
>>> def add(x,y):
>>> return x + y
>>> add(y = 4,x = 3)
7
- 可变数量参数
1.arg:以元组形式返回
2.**arg:以字典形式返回
>>> def test_fun(a,b = 6,*c,**d):
>>> print("a = ",a,"b = ",b,"c = ",c,"d = ",d)
>>> test_fun(1)
a = 1 b = 6 c = () d = {}
>>> test_fun(1,2)
a = 1 b = 2 c = () d = {}
>>> test_fun(1,2,3)
a = 1 b = 2 c = (3,) d = {}
>>> test_fun(1,2,3,4)
a = 1 b = 2 c = (3,4) d = {}
>>> test_fun(a = 1)
a = 1 b = 6 c = () d = {}
>>> test_fun(a = 1,b = 2,c = 3) #c和d是占位符,不是名称,c是不确定数量的单个变量,d是有键有值
a = 1 b = 2 c = () d = {'c': 3}
>>> test_fun(1,2,3,4,x = 1)
a = 1 b = 2 c = (3,4) d = {'x': 1}
>>> test_fun(1,2,3,4,5,6,x = 1,y = 2,z = 3)
a = 1 b = 2 c = (3, 4, 5, 6) d = {'x': 1, 'y': 2, 'z': 3}
>>> test_fun(1,2,3,4,b = 8) #b不能二次赋值
TypeError: test_fun() got multiple values for argument 'b'
2. 函数的定义
def 函数名([参数列表]):
函数体
注:’’‘可以用来注释’’’
>>> def fun():
>>> '''This is a function
>>> it will realize some function'''
>>> print('Hi,welcome to my function')
>>> help(fun)
fun()
This is a function
it will realize some function