有没有办法让下面的代码:
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
?
我尝试使用模块“检查”但没有成功...
朱利安
EDIT:
The point here is for 'log' function to be able to retrieve its caller name on its own (using traceback, inspect, or any mean necessary).
I do not want to pass the class name, or anything else than 'message' to the 'log' function.
最佳答案
所以我终于想出了这个方法:
#!/usr/bin/env python3
def log(message):
import inspect
import gc
code = inspect.currentframe().f_back.f_code
func = [obj for obj in gc.get_referrers(code) if inspect.isfunction(obj)][0]
print(func.__qualname__, message)
它需要 python3 以便可以使用 __qualname__。
关于Python:如何获取我所在函数的*完整*名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45470346/