程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python partial function

編輯:Python

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
  • If you do not use keyword parameters , Use it directly :double = partial(multiply, 2), be 2 Yes, it is multiply The leftmost parameter , namely x = 2;( It will assign values from left to right by default , Multiple values can be passed )
  • call double When the method is used , If no keyword parameter is used , The default value is also from Left to right assignment ;
  • If partial In the function Parameters have been specified , call double When the method is used , The value passed in after the parameter needs to be specified ;
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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved