考虑一下这个简单的装饰演示:
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.bar和d._decorator的类型确认为<class 'method'>。
print(type(d.bar))
print(type(d._decorator))现在,如果在定义bar方法之前修改上述代码以定义_decorator方法,则会得到错误。
@_decorator
NameError: name '_decorator' is not defined为什么在上述情况下,方法的排序是相关的?
发布于 2015-08-19 15:32:01
因为修饰的方法实际上不是看起来的“方法声明”。修饰器语法suger隐藏的内容如下:
def bar( self ) :
print ("the mundane")
bar = _decorator(bar)如果将这些行放在_decorator定义之前,名称错误并不令人惊讶。就像丹尼尔·罗斯曼说的那样,类主体只是代码,它是从上到下执行的。
https://stackoverflow.com/questions/32096706
复制相似问题