关于Python的装饰器,之前一直很少用,看文章也是一知半解。总是不能理解装饰器的调用顺序,今天突发奇想用dir查询属性列表,终于解惑了。我们从下面这个最经典的装饰器例子来说明。
def outer(func):
def inner():
return func()+1
return inner
@outer
def foo():
return 1
print(foo())
在上面的例子中,调用的是foo函数,foo函数因为装饰器的原因调用了outer函数对原函数进行装饰。我的疑问就是在这时候产生的,outer函数返回的是inner函数的定义,并没有返回inner函数执行,为什么在代码中却能执行inner函数?
其实答案很简单,我们看下面这段代码就明白了
def outer(func):
def inner():
return func()+1
return inner
@outer
def foo():
return 1
def foo2():
return 2
print(foo.__name__, '\n')
print(foo.__code__, '\n')
print(foo2.__name__, '\n')
print(foo2.__code__, '\n')
输出
inner
<code object inner at 0x000001ED9C8C6B70, file " G:/Untitled-1.py", line 2>
foo2
<code object foo2 at 0x000001ED9C9A7A50, file "G:/Untitled-1.py", line 11>
从上面这段代码中我们可以看到,foo函数在定义的时候,其__name__和__code__属性已经改变了,其指向已经变成了修饰过后的foo函数,即inner函数。这样的话,代码的调用顺序就十分清晰明了了,代码是直接就调用了修饰后的函数,而不是在执行到使用了装饰器的函数时再去修饰。
若有错误,欢迎指正。_(°ω°」∠)_