装饰工姓名

2024-03-29 13:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

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

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

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

     @_decorator
NameError: name '_decorator' is not defined

为什么上面的排序是相关的?在


Tags: 方法代码selfreturn定义deftypebar
1条回答
网友
1楼 · 发布于 2024-03-29 13:30:38

因为修饰的方法实际上并不像看上去那样是一个“方法声明”。decorator语法suger隐藏的是:

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

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

相关问题 更多 >