简体   繁体   中英

How does this decorator work in python

I had this decorator written by someone else in code and i am not able to get it

def mydecorator(a, b):
        def f1(func):
            def new_func(obj):
                try:
                    f= func(obj) 
                except Exception as e:
                    pass
                else:
                    if f is None:
                        pass
                    else:
                        f = f, a, b

                return f
            return new_func
        return f1

This is applied to function like this

@mydecorator('test1', 'test2')
def getdata():
   pass

My thinking was that decorator takes function name as argument but here

i am not able to get from where did func came and obj came

This -

@mydecorator('test1', 'test2')
def getdata():
   pass

is similar to (without the decofunc name ever being created) -

decofunc = mydecorator('test1', 'test2')
@decofunc
def getdata():
   pass

Since mydecorator() returns f1 , which accepts the function as the argument.

Then it gets the getdata function as argument. and returns the new_func , and the name getdata is replaced with this new_func , hence whenever you call getdata() it calls this new_func function, which internally calls your original getdata() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM