python - Decorator NameError -
consider simple decorator demo:
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()
running gives expected output:
now decorated mundane
the type d.bar
, d._decorator
confirm <class 'method'>
if add following 2 lines end of above code.
print(type(d.bar)) print(type(d._decorator))
now if modify above code define bar
method before defining _decorator
method, error
@_decorator nameerror: name '_decorator' not defined
why ordering of methods relevant in above case ?
because decorated method not 'method declaration' seems. decorator syntax suger hides this:
def bar( self ) : print ("the mundane") bar = _decorator(bar)
if put these lines before definition of _decorator
, name error doesn't come surprise. @daniel roseman said, class body code, executed top bottom.
Comments
Post a Comment