gpt4 book ai didi

python - 为什么要使用partial给函数添加属性

转载 作者:行者123 更新时间:2023-12-04 00:00:35 25 4
gpt4 key购买 nike

我读了this前几天的文章,我不明白为什么 partial 在“Logging Decorators”部分中使用:

def attach_wrapper(obj, func=None):  # Helper function that attaches function as attribute of an object
if func is None:
return partial(attach_wrapper, obj)
setattr(obj, func.__name__, func)
return func

attach_wrapper 未用于在包装另一个函数的函数上设置一些属性:

@attach_wrapper(wrapper)  # Attaches "set_level" to "wrapper" as attribute
def set_level(new_level): # Function that allows us to set log level
nonlocal level
level = new_level

为什么不能用setattr直接在wrapper上设置这些属性?

最佳答案

它的用途是,如果 attach_wrapper 函数在没有包装函数的情况下被调用,它会返回一些东西,然后您可以调用其他函数来将多个附加到目标对象。例如,如果您有三个函数 fgh,以及一个对象 foo,您可以使用 attach_to_foo = attach_wrapper(foo) 创建一个“attacher”,然后将其与 attach_to_foo(f)attach_to_foo(g) 一起使用code>attach_to_foo(h)foo.ffoo.gfoo.h 结束。

关于python - 为什么要使用partial给函数添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62503752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com