这个装饰器如何在python中工作

use*_*546 5 python python-decorators

我有这个装饰由别人写的代码,我无法得到它

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
Run Code Online (Sandbox Code Playgroud)

这适用于这样的功能

@mydecorator('test1', 'test2')
def getdata():
   pass
Run Code Online (Sandbox Code Playgroud)

我的想法是装饰器将函数名称作为参数但在这里

我无法func从哪里来,obj来了

Ana*_*mar 4

这 -

@mydecorator('test1', 'test2')
def getdata():
   pass
Run Code Online (Sandbox Code Playgroud)

类似于(没有decofunc创建名称)-

decofunc = mydecorator('test1', 'test2')
@decofunc
def getdata():
   pass
Run Code Online (Sandbox Code Playgroud)

由于mydecorator()returns f1,它接受函数作为参数。

然后它获取getdata函数作为参数。并返回new_func,并且名称getdata被替换为 this new_func,因此每当您调用getdata()它时都会调用此new_func函数,该函数在内部调用您的原始getdata()函数。