python functools.partial的功能

时间:2012-11-15 10:21:45

标签: python

我有以下代码:

import functools
import random
import inspect 

def myfirst(a, b):
    return a + b

def mysecond(c, d):
    return c - d

def returnAPartial():  
    myrand = random.randrange(0,2)
    if myrand == 1:
        return functools.partial(myfirst, 1)
    else:
        return functools.partial(mysecond, 2)

我将它加载到python interactive并运行:

myfunc = returnAPartial()

我想(以编程方式)检查myfunc是否是myfirst或mysecond函数的部分应用程序(不是通过计算,示例有点做作)到目前为止我使用inspect.getmembers()但我找不到一个合适的属性来检查?

2 个答案:

答案 0 :(得分:4)

partial objects具有func属性,这是您想要的:

 myfunc = returnAPartial()
 print myfunc.func # <function mysecond at 0x10c918488>

答案 1 :(得分:1)

内部help命令可以给你一些提示:

>import _functools
>help(_functools.partial)
...
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |
 |  args
 |      tuple of arguments to future partial calls
 |
 |  func
 |      function object to use in future partial calls
 |
 |  keywords
 |      dictionary of keyword arguments to future partial calls
 |