[英]Python: Create class whose constructor accepts a user-given function which becomes a method
Is it possible in python (3) to have a class whose constructor takes as an argument a function which is then converted into a method on that instance?在 python (3) 中是否有可能有一个 class 的构造函数将 function 作为参数,然后将其转换为该实例上的方法?
I want to do something like:我想做类似的事情:
class Example:
def __init__(self, val1, val2, user_passed_function):
self.val1 = val1
self.val2 = val2
# this next line doesn't quite get what I'm going for...
self.upf = user_passed_function
def user_function_doer(self, *args, **kwargs):
# THIS LINE IS KEY
return self.upf(*args, **kwargs)
def upf1(instance, arg):
return instance.val1 + arg
def upf2(instance, arg):
return instance.val2 + arg
and then have the following:然后有以下内容:
ex1 = Example(1, 2, upf1)
ex1.user_function_doer(10)
## should return 1 + 10 = 11
ex2 = Example(1, 2, upf2)
ex2.user_function_doer(10)
## should return 2 + 10 = 12
My actual use case is a bit more complicated than this, but basically I want to be able to pass a function at instantiation time that, later on, will have the ability to access attributes on the instance.我的实际用例比这要复杂一些,但基本上我希望能够在实例化时传递一个 function,以便稍后能够访问实例上的属性。
Possible?可能的?
I believe if I change the line after the # THIS LINE IS KEY
comment to read:我相信如果我将
# THIS LINE IS KEY
评论之后的行改为:
def user_function_doer(self, *args, **kwargs):
# THIS LINE IS KEY
return self.upf(self, *args, **kwargs)
things might work out ok.事情可能会顺利进行。 But it feels odd to need to write the
self
argument explicitly there...for actual instance methods it would be passed automatically.但是需要在那里显式地编写
self
参数感觉很奇怪……对于实际的实例方法,它将自动传递。 Is there a way to get that to happen?有没有办法让它发生?
You have mentioned an instance
argument in the definition of upf1
and upf2
您在
upf1
和upf2
的定义中提到了一个instance
参数
but do not pass self
in return self.upf(*args, **kwargs)
但不要通过
self
作为return self.upf(*args, **kwargs)
return self.upf(self,*args, **kwargs)
solves that and seems to work as expected return self.upf(self,*args, **kwargs)
解决了这个问题,并且似乎按预期工作
Also... you are missing the self
in def user_function_doer(self,*args, **kwargs):
另外...您在
def user_function_doer(self,*args, **kwargs):
中缺少self
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.