gpt4 book ai didi

python - 为什么 functools.partial 没有被检测为 types.FunctionType?

转载 作者:行者123 更新时间:2023-11-30 22:32:23 31 4
gpt4 key购买 nike

在我的代码中,我需要检测变量是否是函数并对其执行一些操作。

一切都很顺利,直到我现在使用 functools 创建了一个部分函数,​​突然我的一些测试失败了:

import types
import functools

def f(s):
print(s)

l = lambda s: print(s)

pf = functools.partial(f, 'Hello World')
pl = functools.partial(l, 'Hello World')
test_f = isinstance(f, types.FunctionType) # True
test_l = isinstance(l, types.FunctionType) # True
test_pf = isinstance(pf, types.FunctionType) # False
test_pl = isinstance(pl, types.FunctionType) # False

为什么它们之间有区别?两种类型都是可调用的...更重要的是,如果我不能使用 types.FunctionType,我如何检测某个变量是否是一个函数,即使它是一个部分函数?

最佳答案

functools.partial是一个带有 __call__ 方法的,它在文档中说:

Return a new partial object which when called will behave like func

(粗体强调是我添加的)

我们可以在 Python REPL 中确认这一点:

>>> from functools import partial
>>> add_one = partial(sum, 1)
>>> type(add_one)
<class 'functools.partial'>

Python 的等价物是这样的:

class Partial:

def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs

def __call__(self, *args, **kwargs):
return self.func(*self.args, *args, **self.kwargs, **kwargs)

因此它围绕函数创建了一个简单的包装对象,而这样的对象根本就不是函数。 types.FunctionType 仅适用于实际函数。

您正在寻找的是一种检查对象是否可调用的方法,为此您可以使用内置 callable功能:

>>> callable(sum)
True
>>> callable(3)
False
>>> callable(functools.partial(sum, 1))
True

关于python - 为什么 functools.partial 没有被检测为 types.FunctionType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45485017/

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