装饰者NameError

时间:2015-08-19 13:20:09

标签: 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()

运行它会得到预期的输出:

now decorated
the mundane

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

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

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

     @_decorator
NameError: name '_decorator' is not defined

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

1 个答案:

答案 0 :(得分:4)

因为装饰方法实际上并不是一种方法声明&#39;看起来像。装饰器语法suger隐藏的是:

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

如果您将这些行放在_decorator的定义之前,则名称错误并不令人惊讶。就像@Daniel Roseman所说,类体只是代码,从上到下执行。

相关问题