[英]Python, How to pass function to a class method as argument
I am trying write a signal processing package, and I want to let user creates a custom function without needing to access the class file : 我正在尝试编写一个信号处理包,我想让用户创建自定义函数而无需访问类文件:
class myclass():
def __init__(self):
self.value = 6
def custom(self, func, **kwargs):
func(**kwargs)
return self
c = myclass()
def add(**kwargs):
self.value += kwargs['val']
kwargs = {'val': 4}
c.custom(add, **kwargs )
print (c.value)
I got name 'self' is not defined. 我没有定义“自我”这个名字。 Of course because func is not a method to the class.
当然,因为func不是该类的方法。 But I am not sure how to fix it.
但是我不确定如何解决它。 Please advice.
请指教。
Thanks 谢谢
You can explicitly pass the self
argument to add
: 您可以显式传递
self
参数来add
:
class myclass():
def __init__(self):
self.value = 6
def custom(self, func, **kwargs):
func(self, **kwargs)
return self
c = myclass()
def add(self, **kwargs):
self.value += kwargs['val']
kwargs = {'val': 4}
c.custom(add, **kwargs )
print (c.value)
Output: 输出:
10
You need to pass the class instance into the method too, do this : 您也需要将类实例传递到方法中,执行以下操作:
class myclass():
def __init__(self):
self.value = 6
def custom(self, func, **kwargs):
func(self, **kwargs) ## added self here
return self
c = myclass()
def add(self, **kwargs): ## added self here
self.value += kwargs['val']
kwargs = {'val': 4}
c.custom(add, **kwargs )
print (c.value)
output : 10
输出:
10
I would do one of the following: 我将执行以下操作之一:
1) Make the custom method a method of the class. 1)使自定义方法成为类的方法。
class myclass():
def __init__(self):
self.value = 6
def custom(self, func, **kwargs):
func(**kwargs)
return self
def add(self, **kwargs):
self.value += kwargs['val']
kwargs = {'val': 4}
c = myclass()
c.custom( c.add, **kwargs )
print (c.value) # Result == 10
2) Do not give the custom value itself access to class variables. 2)不要让自定义值本身访问类变量。
class myclass():
def __init__(self):
self.value = 6
def custom(self, func, **kwargs):
self.value += func(**kwargs)
return self
def add(**kwargs):
return kwargs['val']
kwargs = {'val': 4}
c = myclass()
c.custom(add, **kwargs )
print (c.value) # Result == 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.