views:

85

answers:

3

Here's 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's parent class's 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?

+2  A: 
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
jldupont
Really, thanks for that bit of info!
orokusaki
+1  A: 

Please notice in this context that the use of "self" is just a convention, a method just 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')
snies
+1  A: 

The self argument is passed as the first argument. Also your MyDecorator is a class emulating a function. Easier to make it an actual function.

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()
Paul Hankin
Thanks for the answer but that's not what I was asking. I'm looking to access the class instance from inside the class decorator. Check jldupont's answer.
orokusaki