Parameters

1)positional,keyword and default parameter
For positional parameters,values are assigned to different parameters according to their positions;  
def hello_1(greeting, name):
    print '%s, %s!' % (greeting, name)
>>> hello_1('Hello', 'world')
Hello, world!
Sometimes (especially if you have many parameters) the order may be hard to remember. To make things easier, you can supply the name of your parameter:
>>> hello_1(greeting='Hello', name='world')
Hello, world!
>>> hello_1(name='world', greeting='Hello')
Hello, world!
The parameters that are supplied with a name like this are called keyword parameters.On their own, the key strength of keyword parameters is that they can help clarify the role of each parameter.
What really makes keyword arguments rock, however, is that you can give the parameters in the function default values:
def hello_3(greeting='Hello', name='world'):
    print '%s, %s!' % (greeting, name)
>>> hello_3()
Hello, world!
2)collecting parameters  
In the definition of function,such as def func(*param),  the star means adding tuple mark "()" for the function arguments
def print_params(*params):
    print params
>>> print_params(1, 2, 3)
(1, 2, 3)
for def func(**param) the double stars means adding dictionary mark "{}" for the function arguments
def print_params_3(**params):
    print params
>>> print_params_3(x=1, y=2, z=3)
{'z': 3, 'x': 1, 'y': 2}
3)Reversing the Process
we also can use the stars to reverse the process of collecting prarameters when calling the function .that is  " * " means deleting tuple mark and "**" for dictionary mark:
def add(x, y): return x + y
params = (1, 2)
>>> add(*params)
3
def hello_3(greeting='Hello', name='world'):
    print '%s, %s!' % (greeting, name)
>>> params = {'name': 'Sir Robin', 'greeting': 'Well met'}
>>> hello_3(**params)
Well met, Sir Robin!
Using * (or **) both when you define and call the function will simply pass the tuple or dictionary right through, so you might as well not have bothered:
>>> def with_stars(**kwds):
        print kwds['name'], 'is', kwds['age'], 'years old'
>>> def without_stars(kwds):
        print kwds['name'], 'is', kwds['age'], 'years old'
>>> args = {'name': 'Mr. Gumby', 'age': 42}
>>>with_stars(**args)
Mr.Gumby is 42 years old
>>>without_stars(args)
Mr.Gumby is 42 years old
So the stars are really useful only if you use them either when defining a function (to allow a varying number of arguments) or when calling a function (to "splice in" a dictionary or a sequence).


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值