我的代码如下
#!/usr/bin/env python3
def use_logging(func):
def _deco():
print("%s is running" % func.__name__)
func()
return _deco
@use_logging
def bar():
print('i am bar')
当我执行bar()
时,输出是
bar is running
i am bar
当我执行use_logging(bar)()
时,输出具有_deco is running
输出:
_deco is running
bar is running
i am bar
我想知道为什么在执行use_logging(bar)()
时会显示_deco is running
,以及它是如何工作的
另外,我在def _deco():
之前添加了print ("hhhhhhh")
,代码如下:
def use_logging(func):
print ("hhhhhhh")
def _deco():
print ("_deco func")
print("%s is running" % func.__name__)
func()
return _deco
@use_logging
def bar():
print('i am bar')
当我再次执行use_logging(bar)()
时,输出为:
hhhhhhh
hhhhhhh
_deco func
_deco is running
_deco func
bar is running
i am bar
这些first two lines
都是“hhhhhh”,你能告诉我the second
“hhhhhhh”出现的原因吗
因为当你这样做的时候:
完成后:
您正在装饰上次调用时从装饰程序返回的函数。这就是语法糖:
和日志记录返回内部定义的
_deco
函数。注意,如果您:你会得到:
相关问题 更多 >
编程相关推荐