Skip to content Skip to sidebar Skip to footer

Python Member Function Decorators Use Instance As A Parameter

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 w

Solution 1:

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:

deffoo(func):
    defwrap(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 itreturn wrap

classA:
    defma(self):
        print"this is ma"    @foo     # if the way foo wraps mb doesn't depend on some arg, don't use args heredefmb(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.

Post a Comment for "Python Member Function Decorators Use Instance As A Parameter"