2017-08-02 41 views
6

功能的*全*名字有没有一种方法,使下面的代码:的Python:如何让我在

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'函数,而不是'message' 。

+1

你可以使用['__qualname__'](https://www.python.org/dev/peps/pep-3155/)吗? – mgilson

+0

https://stackoverflow.com/questions/10973362/python-logging-function-name-file-name-line-number-using-a-single-file –

+0

@mgilson给出了问题中的python2.x语法I' d猜不? –

回答

-1

inspect模块是非常强大的,并且可以以类似的方式来使用traceback得到函数的名称的方式,以及可能还有类名。但是,你可以简单地利用你有self实例变量的事实,它知道自己的类型/类:

import inspect 

class cls(object): 
    def f1(self): 
     this_class_name = type(self).__name__ 
     this_func_name = inspect.currentframe().f_code.co_name 
     print(this_class_name, this_func_name) 

mycls = cls() 
mycls.f1() 
+0

你是对的。但是,我真正想要实现的(对不起,我没有在我的问题中明确提出)是从traceback中检索类名,而不需要将它作为参数传递给我的“日志”函数。 –

0

于是,我终于想出了这个方法:

#!/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__。