为什么在装饰器显示中显示内部函数名?

2024-05-15 01:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下

#!/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”出现的原因吗


Tags: 代码namereturnisuseusrloggingdef
1条回答
网友
1楼 · 发布于 2024-05-15 01:21:12

因为当你这样做的时候:

use_logging(bar)() 

完成后:

@use_logging
def bar():
  print('i am bar')

您正在装饰上次调用时从装饰程序返回的函数。这就是语法糖:

bar = use_logging(bar)

和日志记录返回内部定义的_deco函数。注意,如果您:

print(bar)

你会得到:

<function use_logging.<locals>._deco at 0x7fa2c50473a0>

相关问题 更多 >

    热门问题