我喜欢将具有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))
这可能吗?
答案 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))