【发布时间】:2018-01-10 05:46:12
【问题描述】:
有没有办法让下面的代码:
import traceback
def log(message):
print "%s: %s" %(traceback.extract_stack()[0:-1][-1][2], message)
def f1():
log("hello")
class cls(object):
def f1(self):
log("hi there")
f1()
mycls = cls()
mycls.f1()
显示:
f1: hello
cls.f1: hi there
代替:
f1: hello
f1: hi there
?
我尝试使用模块“检查”但没有成功...
朱利安
编辑:
这里的重点是'log'函数能够检索它的调用者 单独命名(使用回溯、检查或任何必要的手段)。
我不想传递类名或“消息”以外的任何其他内容 到“日志”功能。
【问题讨论】:
-
你能用
__qualname__吗? -
@mgilson 给出了问题中的 python2.x 语法,我猜不是?
-
@AnthonySottile -- 是的,我自己只是得出这个结论 -- 尽管 pypi (pypi.python.org/pypi/qualname) 上有一个(不完美的)替代品
-
@AnthonySottile -- 另外,从
frame对象,我认为您实际上没有对函数对象的引用 -- 只有它的名称。