Python: How to access a decorated instance of a class from inside a class decorator?

Here is an example of what I mean:

class MyDecorator(object): def __call__(self, func): # At which point would I be able to access the decorated method parent class instance? # In the below example, I would want to access from here: myinstance def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper class SomeClass(object): ##self.name = 'John' #error here name="John" @MyDecorator() def nameprinter(self): print(self.name) myinstance = SomeClass() myinstance.nameprinter() 

Do I need to decorate the actual class?

+6
python decorator
source share
3 answers
 class MyDecorator(object): def __call__(self, func): def wrapper(that, *args, **kwargs): ## you can access the "self" of func here through the "that" parameter ## and hence do whatever you want return func(that, *args, **kwargs) return wrapper 
+7
source share

In this context, note that using the self is just a convention; the method simply uses the first argument as a reference to the instance object:

 class Example: def __init__(foo, a): foo.a = a def method(bar, b): print bar.a, b e = Example('hello') e.method('world') 
+2
source share

The self argument is passed as the first argument. Also your MyDecorator is a class that emulates a function. It’s easier to make it a real feature.

 def MyDecorator(method): def wrapper(self, *args, **kwargs): print 'Self is', self return method(self, *args, **kwargs) return wrapper class SomeClass(object): @MyDecorator def f(self): return 42 print SomeClass().f() 
+1
source share

All Articles