Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python member function decorators use instance as a parameter

Tags:

python

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"
like image 735
simon Avatar asked Apr 12 '26 04:04

simon


1 Answers

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.

like image 140
Thomas Avatar answered Apr 13 '26 18:04

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!