python 默认参数与关键字参数

如下函数定义

def hello(name, age=10, gender='F'):

    print 'User Info:'

   print 'name is %s' % name

   print 'age is %d' % age

   print 'gender is %c' % gender

我们的调用方式主要有一下几种

hello('Jim')

hello('Jim', 11)

hello('Jim', 11, 'M')

以上三种是使用默认参数的方式,和C++类似

hello('Jim', age=11)

hello('Jim', gender='M')

hello('Jim', age='11', gender='M')

这上面三种则是使用关键字参数的方式,关键字参数之间的顺序无所谓

hello('Jim', 11, gender='M')

这是混合使用默认参数和关键字参数

但如下调用方式是不行的

hello('Jim', age=11, 'M') 错误的调用方式,关键字参数只能出现在最后

猜你喜欢

转载自blog.csdn.net/tang05709/article/details/81209033