一、位置参数
根据参数的位置来传递参数,调用函数时,传递的参数顺序和个数必须和定义时完全一致
# 定义函数 def man(name, age): print("My name is %s,I am %d years old." % (name, age)) # 调用函数 >>> man('eastonliu',32) My name is eastonliu,I am 32 years old. # 调用时传入的参数顺序必须和定义时一致 >>> man(32, 'eastonliu') Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> man(32, 'eastonliu') File "C:/Users/lmj/AppData/Local/Programs/Python/Python36/2.py", line 2, in man print("My name is %s,I am %d years old." % (name, age)) TypeError: %d format: a number is required, not str # 调用时传入的参数个数必须和定义时一致 >>> man("eastonliu") Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> man("eastonliu") TypeError: man() missing 1 required positional argument: 'age'
二、默认参数
定义函数时,为参数提供默认值,调用函数时,可传可不传该默认参数的值。如果不传就取默认值,传了的话就取传入的值。定义和调用函数时,所有位置参数必须在默认参数前面
# 正确的定义方式 def man(name, age=18): print("My name is %s,I am %s years old." % (name, age)) # 错误的定义方式 def man(age=18, name): print("My name is %s,I am %s years old." % (age, name)) # 调用时默认参数不传则取默认参数 >>> man("eastonliu") My name is eastonliu,I am 18 years old. # 调用时默认参数传值则取传入的值 >>> man("eastonliu",32) My name is eastonliu,I am 32 years old.
三、关键字参数
调用函数时,通过“键-值”形式指定参数
# 定义函数 def man(name, age): print("My name is %s,I am %d years old." % (name, age)) # 调用函数 >>> man(name="eastonliu",age=32) My name is eastonliu,I am 32 years old. # 关键字参数不分顺序 >>> man(age=32, name="eastonliu") My name is eastonliu,I am 32 years old. # 位置参数必须在关键字参数前面 >>> man("eastonliu",age=32) My name is eastonliu,I am 32 years old. >>> man(name="eastonliu",32) SyntaxError: positional argument follows keyword argument
四、参数收集
在函数定义的时候,用*和**来收集位置参数和关键字参数,这样用户在调用函数时,可以给函数提供任意多的参数
1、收集位置参数
def print_params(*params): print(params) # 调用 >>> print_params(1,2,3,4,5) (1, 2, 3, 4, 5)
2、收集关键字参数
def print_params(**params): print(params) # 调用 >>> print_params(x=1,y=2,z=3) {'x': 1, 'y': 2, 'z': 3} # 联合使用 def print_params(x,y,z=6,*pospar,**keypar): print(x,y,z) print(pospar) print(keypar) >>> print_params(1,2,3,8,9,10,foo=12,bar=16) 1 2 3 (8, 9, 10) {'foo': 12, 'bar': 16}
五、参数解包
在调用函数的时候,使用*和**来解包元组或字典形式参数
def add_demo(a,b,c) print(a+b+c) # 解包元组 >>> params=(1,2,3) >>> add_demo(*params) 6 # 解包字典 >>> d = {'a':1,'b':2,'c':3} >>> add_demo(**d) 6