Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, How to pass function to a class method as argument

Tags:

python

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. But I am not sure how to fix it. Please advice.

Thanks

like image 762
J_yang Avatar asked Apr 04 '19 09:04

J_yang


2 Answers

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

like image 102
Mohamed Benkedadra Avatar answered Nov 07 '22 23:11

Mohamed Benkedadra


You can explicitly pass the self argument to 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
like image 30
Cloudomation Avatar answered Nov 07 '22 23:11

Cloudomation