3

How to use instance as a parameter in the python member function decorators. The following is an example.

def foo(func):
    def wrap(s):
        func()
        s.ma()
    return wrap

class A:
    def ma(self):
        print "this is ma"

    @foo(self)     #error.name 'self' is not defined
    def mb(self):
        print "this is mb"
simon
  • 569
  • 9
  • 20
  • 2
    You can't, since not only the instance but the class is not yet defined while the class block is executing. What are you trying to accomplish that makes you think you need to do this? – BrenBarn Feb 07 '13 at 06:49
  • 1
    Furthermore, your foo decorator is not set up to take arguments. Do you just want to have a reference to the instance in your foo decorator function? `wrap`'s parameter `s` will be bound to the instance, you should pass it on to `func` as in `func(s)`. – Thomas Feb 07 '13 at 07:16

1 Answers1

2

It's not clear what you're looking for, but if you want to be able to use the reference to the instance inside your decorator:

def foo(func):
    def wrap(s): # I'd call this 'self' instead of 's' to remind us it's a reference to an instance

        func(s) # This is a function, not a method yet - so we need to pass in the reference

        s.ma() # This is a method, because you use attribute lookup on the object s to get it
    return wrap

class A:
    def ma(self):
        print "this is ma"

    @foo     # if the way foo wraps mb doesn't depend on some arg, don't use args here
    def mb(self):
        print "this is mb"

I think you're confused here about the difference between methods and functions in Python – you seem to expect func will work like a method, when in fact it will still be a function when it is being decorated. It is the decorated function that will, at attribute lookup on the instance, be turned into a method; this means you still need the explicit self when you call func in your wrapper function.

See the terrific answer to How to make a chain of function decorators? for a better explanation of what's going on.

Community
  • 1
  • 1
Thomas
  • 6,515
  • 1
  • 31
  • 47