Recently I came across partial This function , I don't understand , I found out later This is mainly to pass the default value ;
namely :partial The function of the function is : Fix some parameters of a function , Returns a new function .
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, y=2)
"""
partial Receiver function multiply As a parameter , Fix multiply Parameters of y=2, And return a new function to double;
Be similar to :
def double(x, y=2):
return multiply(x, y)
"""
print(double(3)) # 6
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply,x=1)
# print(double(3)) The direct call will report an error , Parameters need to be specified
# TypeError: multiply() got multiple values for argument 'x'
print(double(y=3)) # 3