调用函数的关键字参数要放在参数列表的后面, 关键字参数放在参数列表的前面会报错
def printPerson( likes, age, name): print('name: %s' % name) print('age: %d' % age) print('likes:', likes) printPerson(name = '小高', age = 13, likes = ['family', 'love']) printPerson(likes = ['family', 'love'], age = 18, '小高')
会报错:positional argument follows keyword argument
def printPerson( name, likes, age, ): print('name: %s' % name) print('age: %d' % age) print('likes:', likes) printPerson('小高', age = 13, likes = ['family', 'love'])
位置参数'小高'会自动地传给第一个形参,剩余的是关键字参数根据形参变量名传参
若第一个位置参数跟第一个形参不对应就会报错,如:
def printPerson( likes, name, age): print('name: %s' % name) print('age: %d' % age) print('likes:', likes) printPerson('小高', age = 13, likes = ['family', 'love'])
TypeError: printPerson() got multiple values for argument 'likes'
因为第一个实参'小高'会自动传给第一个形参likes,而后面的关键字参数likes也会传给形参likes,这样就造成了参数likes两个值报错