装饰器NameError

bha*_*arc 2 python python-decorators

考虑一下这个简单的装饰演示:

class DecoratorDemo():

    def _decorator(f):
        def w( self ) :
            print( "now decorated")
            f( self )
        return w

    @_decorator
    def bar( self ) :
        print ("the mundane")

d = DecoratorDemo()
d.bar()
Run Code Online (Sandbox Code Playgroud)

运行此命令可获得预期的输出:

now decorated
the mundane
Run Code Online (Sandbox Code Playgroud)

的类型d.bard._decorator确认,<class 'method'>好像我将以下两行添加到上述代码的末尾。

print(type(d.bar))
print(type(d._decorator))
Run Code Online (Sandbox Code Playgroud)

现在,如果我在定义bar方法之前修改上述代码以定义方法,则会_decorator收到错误消息

     @_decorator
NameError: name '_decorator' is not defined
Run Code Online (Sandbox Code Playgroud)

在上述情况下,为什么方法的顺序有意义?

Neo*_*ang 5

因为修饰的方法实际上并不是看上去的“方法声明”。suger隐藏的装饰器语法是这样的:

def bar( self ) :
    print ("the mundane")
bar = _decorator(bar)
Run Code Online (Sandbox Code Playgroud)

如果将这些行放在的定义之前_decorator,那么名称错误就不足为奇了。就像@Daniel Roseman所说的那样,类主体只是代码,是自上而下执行的。