装饰器名称错误

Decorator NameError

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

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()

运行 这给出了预期的输出:

now decorated
the mundane

如果我在上面的代码末尾添加以下两行,d.bard._decorator 的类型确认为 <class 'method'>

print(type(d.bar))
print(type(d._decorator))

现在如果我在定义 _decorator 方法之前修改上面的代码以定义 bar 方法,我会得到错误

     @_decorator
NameError: name '_decorator' is not defined

为什么方法的顺序与上述情况相关?

因为装饰方法实际上并不是看起来的 'method declaration'。 suger 隐藏的装饰器语法是这样的:

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

如果将这些行放在 _decorator 的定义之前,名称错误就不足为奇了。正如@Daniel Roseman 所说,class 主体只是代码,从上到下执行。