如何将函数传递给具有特定参数的类?

时间:2019-12-15 11:20:11

标签: python

我喜欢将具有2个参数的函数传递给其中1个参数为“预定义”的类。当我从类实例中调用函数时,我只想提供第二个变量(因为我已经定义了第一个)。示例:

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

class MyClass():
    def __init__(self, fun):
        self._fun = fun

    def class_function(self, c):
        return self._fun(c)


instance = MyClass(my_fun(a=5.0))
print(instance.class_function(10.0))

这可能吗?

1 个答案:

答案 0 :(得分:1)

使用partial模块中的functools

from functools import partial


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


class MyClass():
    def __init__(self, fun):
        self._fun = fun

    def class_function(self, c):
        return self._fun(c)


instance = MyClass(partial(my_fun, 5.0))
print(instance.class_function(10.0))