从内部取
def a():
print("hello")
print(a.__name__)
print(a.__getattribute__('__name__'))
print(getattr(a,'__name__'))
通过sys模块
import sys
def a():
print(sys._getframe().f_code.co_name) # f_code和co_name可以参考python源码解析的pyc生成和命名空间章节
a()
通过inspect模块
import inspect
def get_current_function_name():
return inspect.stack()[1][3]
class MyClass:
def function_one(self):
print("%s.%s invoked" % (self.__class__.__name__, get_current_function_name()))
if __name__ == "__main__":
myclass = MyClass()
myclass.function_one()