获取当前函数名称的方法有多种:最简单的是使用__name__属性,适用于普通函数和方法;在装饰器中应使用functools.wraps保留原函数名;需获取调用栈信息时可用sys._getframe()或inspect.currentframe();inspect模块功能更强大但性能开销略高;多线程环境下推荐通过参数传递函数名或使用inspect确保安全。

想知道Python里当前运行的函数叫啥?其实方法挺多的,而且不同场景可能适合不同的方案。最简单的,直接用
__name__
获取当前函数名称的方法:
直接使用__name__
__name__
def my_function():
print(f"当前函数的名字是: {my_function.__name__}")
my_function() # 输出: 当前函数的名字是: my_function使用sys._getframe()
立即学习“Python免费学习笔记(深入)”;
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
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__
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获取当前函数名称的方法的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号