[英]How to pass function to class with specific arguments?
I like to pass a function which has 2 arguments to a class where 1 of the arguments are "predefined".我喜欢将一个有 2 个参数的函数传递给一个类,其中 1 个参数是“预定义的”。 When I call the function from within a class instance, I only want to give the second variable (because I already defined the first).当我从类实例中调用函数时,我只想给出第二个变量(因为我已经定义了第一个)。 Example:例子:
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))
Is this possible?这可能吗?
Use partial
from functools
module.使用functools
模块中的partial
。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.