Skip to main content
 首页 » 编程设计

python之从 python 对象获取函数的输入

2025年05月04日12JeffreyZhao

我有课。此类具有要由不同程序评估的函数列表。

class SomeClass(object): 
    def __init__(self, context): 
        self.functions_to_evaluate = [] 

有一个函数可以通过类似的方式将函数添加到 SomeClass 的实例中:

new_function = check_number(5) 
SomeClassInstance.functions_to_evaluate.append(new_function) 

假设 check_number 是一个函数,它会检查 number 是否大于 10。

如果我使用 SomeClassInstance.functions_to_evaluate 并打印它,我会得到一堆 python 对象,如下所示:

<some_library.check_number object at 0x07B35B90> 

我想知道我是否可以提取给 check_number 的输入,例如:

SomeClassInstance.functions_to_evaluate[0].python_feature() 将返回“5”或任何输入到 check_number 的内容。

请您参考如下方法:

你可以使用标准库functools.partial ,它创建了一个新的偏应用函数 *。

>>> from functools import partial 
>>> def check_number(input): 
...     return input > 10 
>>> fn = partial(check_number, 5) 
>>> fn.args  # this attribute gives you back the bound arguments, as a tuple. 
(5,) 
>>> fn()  # calls the function with the bound arguments. 
False 

*:实际上 partial 对象不是 function 实例,但它是一个可调用对象,从 duck 类型的角度来看它是一个函数。