Python Basics ---Chapter6 Abstraction (2)

本文介绍了Python中关键字参数和默认值的使用,包括位置参数、关键字参数的清晰性,以及如何结合两种参数方式。此外,还讲解了收集参数的概念,如利用星号操作符(*)收集多余参数,以及双星号操作符(**)如何将关键字参数转化为字典。最后,解释了**在参数分布和收集过程中的作用。
摘要由CSDN通过智能技术生成


keyword Parameters and Defaults

1. Positional Parameters

The parameters we have been used is called positional parameters, because the position are important–more important than their names.

def hello_1(greeting, name):
    print('{},{}!'.format(greeting,name))
    
def hello_2(name,greeting):
    print('{},{}!'.format(name,greeting))
    
hello_1('hello','world')
hello_2('hello','world')

The output is:

>>>	hello,world!
>>>	hello,world!

You can see that the two functions do exactly the same thing.

2. Keyword Parameters

  • Sometimes (especially if you have many parameters) the order may be hard to remember. To make things easier, you can use keyword parameters to supply the names of your parameters.
store(patient='Mr.Lang',hour=10,minute=20, day=13, month=15)

In functions like store which has a lot of parameters, using keyword parameters can be clearer.

  • The order doesn't matter in keyword parameters.
hello_1(name='world',greeting='hello') 
>>>	hello,world! 
  • What really makes keyword parameters rock is that you can give parameters in the function default values.
def hello_3(greeting='hello',name='world'):
    print('{},{}!'.format(greeting,name))
hello_3()
>>>hello,world!

With the defaulted parameters values, you can call the function without supply any parameter values.

hello_3('Greetings')
>>>Greetings,world!
hello_3('Greetings','universe')
>>>Greetings,universe!

This works well with positional parameters, except that you must supply the greeting if you want to supply the name . If you want to only supply the name, leaving the default value for greeting, you have to use keyword parameters.

hello_3(name='Victor')
>>>hello,Victor!

3. Combine the two way of parameters

def hello_4(name,greeting='Hello',punctuation='!'):
    print('{},{}{}'.format(greeting, name, punctuation))
hello_4('Mars')
>>>Hello,Mars!
hello_4('Mars','Howdy')
>>>Howdy,Mars!
hello_4('Mars','Howdy','...')
>>>Howdy,Mars...
hello_4('Mars',punctuation='.')
>>>Hello,Mars.
hello_4()
>>>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-8ee2b2468f0f> in <module>()
----> 1 hello_4()

TypeError: hello_4() missing 1 required positional argument: 'name'

Collecting Parameters

1. Previous on Sequence Unpacking

  • Sequence Unpacking: I have a sequence (or an arbitrary iterable object) of values, and I unpack it into a sequence of variables.
x,y,z=1,2,3# tuples
print(x,y,z)
>>>1 2 3
x,y,z=[1,2,3]#lists
print(x,y,z)
>>>1 2 3
scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}# dicts
key, value = scoundrel.popitem()
print(key,value)
>>>girlfriend Marion
  • Instead of ensuring that the number of values matches exactly, you can gather up any superfluous ones using the star operator (*). For example:
x,y,*rest=1,2,3,4,5,' ',6,'a'
print(x,y,rest)
>>>1 2 [3, 4, 5, ' ', 6, 'a']

All the rest of the values are assigned into a list. And the starred parameter may occur in other positions than the last.

2. Previous on dict.popitem()

dict.popitem(): Randomly return and delete a pair of keys and values in the dictionary (usually delete the last pair).
If the dictionary is empty, this method is called, and the KeyError exception is reported.

3. Collecting Parameters using *

  • Attention: you construct a tuple when putting a comma at last
x=1,
x
>>>(1,)
  • The star in front of the parameter puts all the values into the same tuple. It gathers them up, so to speak.
def print_param_2(title,*params):
    print(title)
    print(params)
print_param_2('Params:',1,2,3,4,5,6)
>>>Params:
(1, 2, 3, 4, 5, 6)
  • If you don’t give any parameters to gather, params will be a empty tuple.
  • If the starred parameter doesn't occur at the last,you have to specify the parameters after the starred one by name.
  • The star doesn't collect keyword arguments.
def print_param_2(title,*params):
    print(title)
    print(params)
print_param_2('Params:',x=1,y=2,z=3)
>>>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-36fd06750470> in <module>()
      2     print(title)
      3     print(params)
----> 4 print_param_2('Params:',x=1,y=2,z=3)

TypeError: print_param_2() got an unexpected keyword argument 'x'

You can gather them using double star(**) which puts all the parameters in a dictionary.

def print_params_3(**params):
    print(params)
print_params_3(x=1,y=2,z=4)
>>>{'x': 1, 'y': 2, 'z': 4}

Single star collects positional parameters into a tuple, while double star collects keyword parameters into a dict.

4. Reverse process

Using the star (*) and double star (**) to distribute the parameters for positional and keyword parameters. parameters distribution

  • Using sequence like lists and tuples to distribute parameters for positional parameters.
def add(x,y):
	return x+y
params=[1,2]
add(*params)
>>>3
  • Using dictioanary to distribute parameters for key words parameters. And the keys of the dict must be the same as the parameter names of the function.
params={'x':1,'y':2}
def add(**args):
    return args['x']+args['y'] #**args collects all the keyword parameters into a dit
add(**params)
>>>3

For parameters collection, **collects all the keywords parameters into a dict

For parameters distribution, ** distributes the key-value pairs to the parameters of function as keyword parameters

The keys must be the same.

The keys of dict must be strings.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值