g ++]具有很好的变量PRETTY_FUNCTION,其中包含所调用函数的名称。对于函数,它会产生原型(例如,“ void foo(long)”)。对于类中的成员函数,名称包括类名称(例如,“ void Foo :: foo(long)”)。
Python中是否有等效项。我一直在玩“ sys._getframe()”,它很接近,但是似乎没有一个类似的简单机制可以将类名作为成员函数时包含在内。
我喜欢在错误处理程序中使用它。
肯定有人为此拥有神奇的一线……
TIA,
-乔
这是我现在可以获得的最接近的。搜索“ <<
打字Foo。CLNAME有点傻。如果可以通过某种方式将其折叠到外部函数并留在类之外,那就太好了。在Python中必须有一种类似于LINE和NAME的工作方式。
这两个的实现基于我从这里获得的代码:
How to determine file, function and line number?
好东西!
-乔
======
#!/usr/bin/env python
# import system modules
#
import os
import sys
# define a hack to get the function name
#
class __MYNAME__(object):
def __repr__(self):
try:
raise Exception
except:
return str(sys.exc_info()[2].tb_frame.f_back.f_code.co_name)
def __init__(self):
pass
__NAME__ = __MYNAME__()
# define a hack to get the line number in a program
#
class __MYLINE__(object):
def __repr__(self):
try:
raise Exception
except:
return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)
__LINE__ = __MYLINE__()
# use these in a function call
#
def joe():
print("[FUNCTION] name: %s, line: %s" %
(__NAME__, __LINE__)) # <<< here
# use these in a class member function
#
class Foo():
def __init__(self):
Foo.__CLNAME__ = self.__class__.__name__
def joe(self):
print("[CLASS] name: %s::%s, line: %s" %
(Foo.__CLNAME__, __NAME__, __LINE__)) # <<< here
#--------------------------------
# test all this in a main program
#--------------------------------
def main(argv):
# main program
#
print("[MAIN PROGRAM] name: %s, line: %s" %
(__NAME__, __LINE__)) # <<< here
# function call
#
joe()
# class member function
#
foo = Foo()
foo.joe()
# exit gracefully
#
sys.exit(os.EX_OK)
#
# end of main
# begin gracefully
#
if __name__ == "__main__":
main(sys.argv[0:])
#
# end of file