通过functools.partial偏函数可以固定函数中的特定参数,在不使用偏函数时,固定函数的参数需要重新def函数进行调用,具体的使用方式如下所示
def myfun(name,age,major,university):
print("my name is {}, age is {},I majored in {} in {} University".format(name,age,major,university))
def myfun2(major,university):
name,age="zhangshan",21
myfun(name,age,major,university)
def myfun3(name,age):
major,university="Pedagogy","HuBei"
myfun(name,age,major,university)
myfun("liming",18,"conputer","HuNan")
myfun2("Normal","Beijin Normal")
myfun3("wangwu",19)
代码执行输出如下所示 my name is liming, age is 18,I majored in conputer in HuNan University my name is zhangshan, age is 21,I majored in Normal in Beijin Normal University my name is wangwu, age is 19,I majored in Pedagogy in HuBei University
在使用 functools.partial偏函数时,可以更为简洁的固定函数的参数,可以看到使用偏函数库,代码更为简洁。在博主接触的代码中,偏函数常用于深度学习中conv、pool、batchnorm等layer的参数的固定。
import functools
def myfun(name,age,major,university):
print("my name is {}, age is {},I majored in {} in {} University".format(name,age,major,university))
#以args的方式绑定参数,对顺序敏感 参数是从左到右
myfun2 = functools.partial(myfun,"zhangshan",21) #构建偏函数
#以kwargs的方式绑定参数,对顺序不敏感
myfun3 = functools.partial(myfun, major="Pedagogy",university="HuBei") #构建偏函数
myfun("liming",18,"conputer","HuNan")
myfun2("Normal","Beijin Normal")
myfun3("wangwu",19)
代码执行输出如下所示 my name is liming, age is 18,I majored in conputer in HuNan University my name is zhangshan, age is 21,I majored in Normal in Beijin Normal University my name is wangwu, age is 19,I majored in Pedagogy in HuBei University
补充知识 :
args 全称arguments 表示参数,通过下标取值,对顺序敏感
kwargs 全称keyword arguments 表示关键字和参数,通过keyword取值,对顺序不敏感
#args 全称arguments 表示参数,通过下标取值,对顺序敏感
#kwargs 全称keyword arguments 表示关键字和参数,通过keyword取值,对顺序不敏感
def fun(*args, **kwargs):
print("args:",args)
print(args[0])
print("kwargs:",kwargs)
print(kwargs['c'])
a=1
b=2
fun(a,b,c=3,d=4,e=5)
代码执行输出如下所示 args: (1, 2) 1 kwargs: {'c': 3, 'd': 4, 'e': 5} 3