Python,如何将函数作为参数传递给类方法

时间:2019-04-04 09:38:18

标签: python

我正在尝试编写信号处理程序包,我想让用户创建自定义函数而无需访问类文件:

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)

我没有定义名称“ self”。当然,因为func不是该类的方法。但是我不确定如何解决它。请指教。

谢谢

3 个答案:

答案 0 :(得分:4)

您可以将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)

输出:

10

答案 1 :(得分:4)

您还需要将类实例传递给方法, 为此:

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)

输出: 10

答案 2 :(得分:1)

我将执行以下操作之一:

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)不要让自定义值本身访问类变量。

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