想知道Python里当前运行的函数叫啥?其实方法挺多的,而且不同场景可能适合不同的方案。最简单的,直接用
__name__属性就能搞定,但有时候可能需要更高级的技巧,比如在装饰器里获取。
获取当前函数名称的方法:
-
直接使用
__name__
属性: 这是最简单直接的方法,在函数内部使用__name__
会返回函数的名字。def my_function(): print(f"当前函数的名字是: {my_function.__name__}") my_function() # 输出: 当前函数的名字是: my_function
-
使用
sys._getframe()
: 这种方法可以获取调用栈的信息,从而拿到函数名。它稍微复杂一点,但更灵活。import sys def another_function(): frame = sys._getframe() print(f"当前函数的名字是: {frame.f_code.co_name}") another_function() # 输出: 当前函数的名字是: another_function
-
在装饰器里获取函数名: 装饰器场景下,直接用
__name__
可能会拿到装饰器的名字,而不是被装饰的函数。这时可以用functools.wraps
来保留原始函数的信息。import functools def my_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): print(f"被装饰的函数名字是: {func.__name__}") return func(*args, **kwargs) return wrapper @my_decorator def yet_another_function(): pass yet_another_function() # 输出: 被装饰的函数名字是: yet_another_function
-
使用
inspect
模块:inspect
模块提供了更强大的introspection能力,可以用来获取各种代码对象的信息。PIA
全面的AI聚合平台,一站式访问所有顶级AI模型
226 查看详情
import inspect def some_function(): print(f"当前函数的名字是: {inspect.currentframe().f_code.co_name}") some_function() # 输出: 当前函数的名字是: some_function
在类的方法中获取函数名和在普通函数中类似,但需要注意
self参数。
class MyClass: def my_method(self): print(f"当前方法的名字是: {self.my_method.__name__}") # 或者直接用 MyClass.my_method.__name__ instance = MyClass() instance.my_method() # 输出: 当前方法的名字是: my_method
或者,使用
inspect模块:
import inspect class AnotherClass: def another_method(self): print(f"当前方法的名字是: {inspect.currentframe().f_code.co_name}") instance = AnotherClass() instance.another_method() # 输出: 当前方法的名字是: another_method
__name__和
inspect模块,哪个更适合?
__name__属性最简单直接,适合大多数情况。但如果需要更复杂的introspection,比如获取调用栈信息、函数签名等,
inspect模块会更强大。
inspect模块功能更全,但也会带来一些性能开销,所以在对性能有要求的场景下,需要权衡一下。 如何在多线程环境下安全地获取函数名?
多线程环境下,
sys._getframe()可能不是线程安全的。更安全的方法是使用
inspect模块或者直接传递函数名。
import threading import inspect def worker(func_name): print(f"线程中运行的函数名: {func_name}") def my_threaded_function(): thread = threading.Thread(target=worker, args=(inspect.currentframe().f_code.co_name,)) thread.start() my_threaded_function() # 输出: 线程中运行的函数名: my_threaded_function
或者,直接传递函数对象,然后在线程里使用
__name__:
import threading def worker(func): print(f"线程中运行的函数名: {func.__name__}") def my_threaded_function(): thread = threading.Thread(target=worker, args=(my_threaded_function,)) thread.start() my_threaded_function() # 输出: 线程中运行的函数名: my_threaded_function
以上就是python如何获取当前函数的名字_python获取当前函数名称的方法的详细内容,更多请关注知识资源分享宝库其它相关文章!
相关标签: python app Python 栈 线程 多线程 对象 大家都在看: python怎么检查一个键是否存在于字典中_python字典键存在性检查 Python怎么实现一个上下文管理器_Python上下文管理器协议实现 python中怎么给函数设置默认参数_Python函数默认参数设置方法 python中怎么测量一段代码的执行时间? python怎么创建一个虚拟环境_python虚拟环境创建与使用教程
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。