一、参数
1.参数分类:必备参数、关键字参数、默认参数、不定长参数
必备参数:
def function(a, b):
print('I am %s, living on %s.'%(a, b))
function('rose', 'titanic') # output:I am rose, living in titanic.
function('rose') # output:会报错
function('titanic', 'rose') # output:I am titanic, living in rose.
关键字参数:
function(b = 'titanic', a = 'rose')
# output:I am rose, living in titanic. 此时顺序就不会反
function(b = 'titanic', 'rose')
# 报错output:positional argument follows keyword argument
默认值参数:
定义函数时给形参赋值。默认参数必须在必备参数或关键字参数后面。
def function(a, b = 'titanic'):
print('I am %s, living on %s.'%(a, b))
function('titanic')
# output:I am titanic, living on titanic.
不定长参数:
接受剩余的参数
def function(a, b, *c):
print('I am %s, living on %s.'%(a, b))
print(c)
function('rose', 'titanic', 1, 2, 3, 4)
# output:
# I am rose, living on titanic.
# (1, 2, 3, 4) # 默认记为元祖
*c 接受所有未命名的参数(关键字)
**d 接受所有命名的参数(带关键字的)
def function(a, b, *c, **d):
print('I am %s, living on %s.'%(a, b))
print(c)
print(d)
function('rose', 'titanic', 1, 2, 3, 4, age = 18)
# output:
# I am rose, living on titanic.
# (1, 2, 3, 4)
# {'age': 18}
# 带‘=’的接受为字典
# *c必须在**d之前,不然会报错
# 1,2,3,4必须在age = 18之前,顺序不能乱