Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 装饰子与部分函数_Python_Python Decorators_Partial Application - Fatal编程技术网

Python 装饰子与部分函数

Python 装饰子与部分函数,python,python-decorators,partial-application,Python,Python Decorators,Partial Application,我正在努力学习装饰和局部装饰,我想我有点道理。我理解decorator是一种通过将调用decorator的函数的参数传递到decorator中的嵌套函数中,向对象添加附加功能的方法。我对partial的理解是,当我想将参数的数量减少到一个函数时,我可以使用partial。到现在为止,一直都还不错。但是后来我看到了这个代码片段,我不明白为什么\u inner只接受start和end。为什么不pos?在我看来,如果这应该是第三个参数,这是有道理的 def annealer(f): def

我正在努力学习装饰和局部装饰,我想我有点道理。我理解decorator是一种通过将调用decorator的函数的参数传递到decorator中的嵌套函数中,向对象添加附加功能的方法。我对partial的理解是,当我想将参数的数量减少到一个函数时,我可以使用partial。到现在为止,一直都还不错。但是后来我看到了这个代码片段,我不明白为什么
\u inner
只接受
start
end
。为什么不
pos
?在我看来,如果这应该是第三个参数,这是有道理的

def annealer(f): 
    def _inner(start, end): 
        return partial(f, start, end)
    return _inner

@annealer
def sched_lin(start, end, pos):
    return start + pos*(end-start)

f = sched_lin(1,2)
f(1)
OUTPUT: 2

这里的想法是,您可以调用
f(0)
f(0.2)
f(1)
,传递
pos
参数。如果你通过所有3个参数来做偏微分,它将是一个常数函数…我想我的问题有点不清楚,抱歉。我相信我理解那部分(也许)。更重要的是,为什么
\u internal
在参数中只接受
start
end
,而不接受
pos
。在我看到的所有关于decorators的示例中,嵌套函数的参数数与调用函数的参数数相同(
def sched_lin(start,end,post)
annealer
基本上在某种程度上实现了它的函数。它不再是一个3参数函数,而是一个2参数函数,返回一个单参数函数。也就是说,您现在调用的不是
sched_-lin(1,2,3)
,而是
sched_-lin(1,2)(3)
。在我看来,让decorator修改修饰函数的签名只是一种混乱。换句话说,
annealer
decorator返回一个新函数,该函数自动提供了前两个参数。由于最初的
sched_lin()
函数总共定义了三个参数,因此修饰后的版本只需要与最后一个参数一起传递,即
pos
@chepner:我认为,混淆主要是由于没有提供信息的名称:修饰器没有将底层函数变成退火器。对于任意数量的参数,我都使用过类似的修饰符(它返回
partial(partial,f)
),但基于分叉参数列表,我称它为
curry2