简体   繁体   English

functools.partial中的简化签名

[英]a simplified signature in functools.partial

In the official docs to explain functools 10.2. 在官方文档中解释functools 10.2。 functools — Higher-order functions and operations on callable objects — Python 3.7.0 documentation functools-可调用对象上的高阶函数和操作-Python 3.7.0文档

The partial() is used for partial function application which “freezes” some portion of a function's arguments and/or keywords resulting in a new object with a simplified signature . partial()用于部分函数应用程序,该应用程序“冻结”函数的参数和/或关键字的某些部分,从而生成具有简化签名的新对象。 For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two: 例如,partial()可用于创建行为类似于int()函数的可调用对象,其中基本参数默认为两个:

I could understand most of the statement and admit the "freeze" is a delicate and accurate word to describe the context. 我可以理解大部分的声明,并承认“冻结”是描述上下文的精确而精确的词。

What I cannot follow is "a simplified signature", 我无法理解的是“简化签名”,
What kind of signature it refers for? 它指的是哪种签名?

In this context, simplified just means fewer arguments. 在这种情况下, 简化只是意味着更少的参数。 If you have 如果你有

import functools

def func(a, b, x=8, y=9):
    print((a, b, x, y))

simple_func = functools.partial(func, 1, x=2)

, then simple_func ends up a function with one argument a and one keyword argument y : ,然后simple_func结束一个函数,该函数具有一个参数a和一个关键字参数y

>>> simple_func(3, y=4)
(1, 3, 2, 4)

A function signature is the name of the function, its parameters and, strictly speaking, its return type: 函数签名函数的名称,其参数以及严格地说是其返回类型:

mymodule.myfunction(foo, bar=None, *, baz=42)

This is the signature . 这是签名 When you partial ly bind a function, it returns a new function, typically with fewer parameters because you have already bound a few arguments: 当您partial绑定一个函数时,它会返回一个新函数,通常带有较少的参数,因为您已经绑定了一些参数:

partial(mymodule.myfunction, bar='Mike')

The signature of this newly partially bound function is: 这个新的部分绑定的函数的签名是:

func(foo, *, baz=42)

A simpler signature than the original one. 比原始签名更简单的签名。

The signature means how the function is called, if you have a function that needs five strings its signature is 签名表示函数的调用方式,如果您有一个需要五个字符串的函数,则其签名为

foo (st1, st2, st3, st4, st5)

If you now use partial to freeze three of them, it only needs two 如果现在使用partial冻结其中三个,则只需两个

foo (st1, st2)

Which is "simplified" because it needs less parameters. 之所以“简化”是因为它需要较少的参数。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM