Probably I am approaching the problem in the wrong way and there is a simpler solution, but here is my problem.
I have a decorator defined like this:
def my_decorator(argument):
def wrap(f):
def wrapped_f(*args, **kwargs):
.... # does something with argument
return wrapped_f
return wrap
then I defined a class that looks like this:
class MyClass(object):
def __init__(argument):
self.argument = argument
@my_decorator(self.argument) # !this is an error!
def my_method(self):
.... # does something
Clearly what I wrote is wrong because at the decorator level I cannot access self
, but what's the right approach to solve this problem?
You could have the decorator access self.argument
inside wrapped_f
:
def mydecorator(f):
def wrapped_f(self, *args, **kwargs):
argument = self.argument
.... # does something with argument
return f(self, *args, **kwargs)
return wrapped_f
return wrap
If the variable being passed as argument
changes depending on the function being decorated, you can pass it to the decorator as a string and use getattr
to get it from self
:
def my_decorator(arg_name):
def wrap(f):
def wrapped_f(self, *args, **kwargs):
argument = getattr(self, arg_name)
.... # does something with argument
return wrapped_f
return wrap
class MyClass(object):
def __init__(self, argument):
self.argument = argument
@my_decorator("argument")
def my_method(self):
.... does something
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