contents
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 asequence (or an arbitrary iterable object) of values
, and I unpack it into asequence 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.