This is a memo of O'Reilly Japan's book effective python. https://www.oreilly.co.jp/books/9784873117560/ P44~47
Positional arguments to python functions can be passed as keywords as well as directly assigned values. You can also use keyword arguments to pass values to functions in any order.
def remainder(number, divisor):
return number % divisor
print(remainder(20, 7) #Normal pass by value
print(remainder(20, divisor=7)) #Assign to the second argument
print(remainder(number=20, divisor=7)) #Assign to both arguments
print(remainder(divisor=7, number=20)) #Substitute by swapping arguments
>>>
6
6
6
6
However, the positional argument must precede the keyword argument
print(remainder(number=20, 7))
>>>
File "<ipython-input-15-fb0a3eb0541d>", line 1
print(remainder(number=20, 7))
^
SyntaxError: non-keyword arg after keyword arg
Also, each argument can only be used once.
print(remainder(20, number=7))
>>>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-aa02190f8263> in <module>()
----> 1 print(remainder(20, number=7))
TypeError: remainder() got multiple values for argument 'number'
** Keyword arguments have three advantages **
** Consider a program to calculate the flow rate of liquid ** Calculate the amount flowing per hour
# 2.You can set the default value in the function definition
def flow_rate(weight_diff, time_diff, period=1): #Set the default value for period
return(weight_diff / time_diff) * period
weight_diff = 0.5
time_diff = 3
flow_per_second = flow_rate(weight_diff, time_diff) #Default value for period
flow_per_hour = flow_rate(weight_diff, time_diff, period=3600) #Change the value of period
print('%.3f kg per secound' % flow_per_second) #Amount flowing per second
print('%.3f kg per hour' % flow_per_hour) #Amount flowing per hour
>>>
0.167 kg per secound
600.000 kg per hour
#3.Functions can be extended while maintaining backward compatibility
def flow_rate2(weight_diff, time_diff,
period=1, units_per_kg=1):
return ((weight_diff * units_per_kg) / time_diff) * period
pounds_per_hour = flow_rate2(weight_diff, time_diff,
period=3600, units_per_kg=2.2)
print('%.3f pounds per secound' % pounds_per_hour)
>>>
1320.000 pounds per secound
flow_rate2 is a function that extends flow_rate, but is backwards compatible with flow_rate. However, when substituting with a positional argument, if the order of period and units_per_kg is incorrect, the calculation will be incorrect. In this case, it is important to use keyword arguments instead of positional arguments as much as possible.
Recommended Posts