partial和partialmethod有什么区别?

gru*_*dic 7 python python-3.x functools

我发现functoolsPython 3的模块有两个非常相似的方法:partialpartialmethod.

有人可以提供使用每个人的好例子吗?

Eyo*_*nyo 11

partial用于冻结参数和关键字。它创建一个新的可调用对象,部分应用给定的参数和关键字。

from functools import partial
from operator import add

# add(x,y) normally takes two argument, so here, we freeze one argument and create a partial function.
adding = partial(add, 4)
adding(10)        # outcome will be add(4,10) where `4`  is the freezed arguments.
Run Code Online (Sandbox Code Playgroud)

当您想将数字列表映射到函数但保持一个参数冻结时,这很有用。

# [adding(4,3), adding(4,2), adding(4,5), adding(4,7)]
add_list = list(map(adding, [3,2,5,7])) 
Run Code Online (Sandbox Code Playgroud)

partialmethod 是在 python 3.4 中引入的,它旨在作为方法定义在类中使用,而不是直接调用

from functools import partialmethod
class Live:
    def __init__(self):
        self._live = False
    def set_live(self,state:'bool'):
        self._live = state
    def __get_live(self):
        return self._live
    def __call__(self):
        # enable this to be called when the object is made callable.
        return self.__get_live()

    # partial methods. Freezes the method `set_live` and `set_dead`
    # with the specific arguments
    set_alive = partialmethod(set_live, True)
    set_dead = partialmethod(set_live, False)

live = Live() # create object
print(live()) # make the object callable. It calls `__call__` under the hood
live.set_alive() # Call the partial method
print(live())
Run Code Online (Sandbox Code Playgroud)

  • 我想重点是它只适用于类的主体(而不是类的外部)。我检查过,如果你在外面尝试 `live.set_alive =partialmethod(live.set_live, True)` ,你最终会在 `live` 对象上得到一个 `functools.partialmethod` 对象(甚至不可调用),并且在这种情况下上面的例子 `live.set_alive` 是一个 `functools.partial` 对象(可调用) (5认同)
  • 对于“partialmethod”,您使用了与文档完全相同的定义和示例,这没有帮助。“而不是直接可调用”是什么意思?`live.set_alive()`不是直接调用的吗? (3认同)

Gia*_*los 5

正如@HaiVu 在他的评论中所说,在类定义中调用 partial 将创建一个静态方法,而 partialmethod 将创建一个新的绑定方法,该方法在调用时将作为第一个参数传递给 self。