我正在通过以下示例学习“流利的python”之后的装饰器:
registry = []
def register(func):
print("running register(%s)" % func)
registry.append(func)
return func
@register
def f1():
print("runnning f1()")
@register
def f2():
print("running f2()")
def f3():
print("running f3()")
def main():
print("running main()")
print("registry ->", registry)
f1()
f2()
f3()
if __name__ == "__main__":
main()
运行它并通过:
running register(<function f1 at 0x10870ab70>)
running register(<function f2 at 0x1086f58c8>)
running main()
registry -> [<function f1 at 0x10870ab70>, <function f2 at 0x1086f58c8>]
runnning f1()
running f2()
running f3()
然后,我将寄存器的返回结果从return func
更改为返回func()
def register(func):
print("running register(%s)" % func)
registry.append(func)
return func()
运行并获取
running register(<function f1 at 0x108753d08>)
runnning f1()
running register(<function f2 at 0x108753488>)
running f2()
running main()
registry -> [<function f1 at 0x108753d08>, <function f2 at 0x108753488>]
我不能确定两者之间的区别。