如何查看 python 的 functools.partial 修饰的对象?

如何查看 python 的 functools.partial 修饰的对象?

import functools

# 原始函数

def multiply(x, y):

return x * y

# 使用 functools.partial 创建一个新的可调用对象

partial_function = functools.partial(multiply, y=2)

# 查看 partial_function 的类型

print(type(partial_function))

比如上面的代码,输出就是

<class 'functools.partial'>

但是我想知道这个 partial_function 到底修饰了哪个 func 或者 class,怎么知道呢?


回答:

用 partial_function.func

partial object

partial Objects

partial objects are callable objects created by partial(). They have three read-only attributes:

  • partial.funcA callable object or function. Calls to the partial object will be forwarded to func with new arguments and keywords.
  • partial.args The leftmost positional arguments that will be prepended to the positional arguments provided to a partial object call.
  • partial.keywords The keyword arguments that will be supplied when the partial object is called.

partial objects are like function objects in that they are callable, weak referencable, and can have attributes. There are some important differences. For instance, the __name__ and __doc__ attributes are not created automatically. Also, partial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.


回答:

我知道了,可以用 .func 属性获取

import functools

def multiply(x, y):

return x * y

# 使用 functools.partial 创建一个新的可调用对象

partial_function = functools.partial(multiply, y=2)

print(partial_function.func)

输出

<function multiply at 0x100f97eb0>

如果被修饰的是 class,也是一样的

import functools

class Mclass:

def __init__(self,y:int) -> None:

pass

# 使用 functools.partial 创建一个新的可调用对象

partial_function = functools.partial(Mclass, y=2)

print(partial_function.func)

输出

<class '__main__.Mclass'>

以上是 如何查看 python 的 functools.partial 修饰的对象? 的全部内容, 来源链接: utcz.com/p/939027.html

回到顶部