gru*_*dic 7 python python-3.x functools
我发现functoolsPython 3的模块有两个非常相似的方法:partial和partialmethod.
有人可以提供使用每个人的好例子吗?
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)
正如@HaiVu 在他的评论中所说,在类定义中调用 partial 将创建一个静态方法,而 partialmethod 将创建一个新的绑定方法,该方法在调用时将作为第一个参数传递给 self。
| 归档时间: |
|
| 查看次数: |
1286 次 |
| 最近记录: |