可变参数的函数
函数的可变参数,是说函数的参数是可变的不固定的,
可变参数示例:
*arg:代表参数为一个字典
>>> def sum(*arg): ... s=0 ... for i in arg: ... s+=i ... return s ... >>> sum(0,2,3,3,3,3,1) 15 >>>
函数参数的变化:(按值传和按引用传)
1:函数传入的参数为不可变时,对外部的变量就没影响。a=100
2:函数传入的参数为可变时,对外部的变量就有影响。
3:按值传--传入的不是变量对应的内存地址。
4:按引用传--传入的是变量对应的内存地址。
示例2:
>>> def f(*arg,a,b): ... return a ... >>> f(1,2,2,3,3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() missing 2 required keyword-only arguments: 'a' and 'b' >>>
这种定义是不正确的,不管传多少参数都被当成arg了
示例3:
>>> def f(a,b,**kw):
... print(type(kw))
... for k,v in kw.items():
... print(k,v)
...
>>>
>>> f(1,2,a=3,b=4,c=5)
#1代表的是a,2代表的是b,与后面的a=3,b=4,冲突
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for argument 'a'
>>>
>>> f(1,2,c=3,d=4,e=5)
<class 'dict'>
c 3
d 4
e 5
示例4:
#参数中*代表一个元组 #参数中**代表一个字典 def fun(a=2,b=3,*tup,**dic): print (a) print (b) print (tup) print (dic) fun(1,2,3,3,3,3,x=1,y=2,z=3)
运行结果:
/Users/didi/Documents/pycarm/venv/bin/python /Users/didi/Documents/pycharm_workstation/fun.py
1
2
(3, 3, 3, 3)
{'x': 1, 'y': 2, 'z': 3}
Process finished with exit code 0