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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With