新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
python如何獲取函數(shù)名
在Python中,可以使用inspect模塊來(lái)獲取函數(shù)名,以下是詳細(xì)的步驟和示例代碼:

1、導(dǎo)入inspect模塊
import inspect
2、定義一個(gè)函數(shù)
def my_function():
pass
3、使用inspect.currentframe()獲取當(dāng)前幀
frame = inspect.currentframe()
4、使用frame.f_back獲取上一幀(即調(diào)用函數(shù)的幀)
caller_frame = frame.f_back
5、使用caller_frame.f_code獲取代碼對(duì)象
code = caller_frame.f_code
6、使用code.co_name獲取函數(shù)名
function_name = code.co_name
7、打印函數(shù)名
print("Function name:", function_name)
將以上代碼整合在一起:
import inspect
def my_function():
frame = inspect.currentframe()
caller_frame = frame.f_back
code = caller_frame.f_code
function_name = code.co_name
print("Function name:", function_name)
my_function()
運(yùn)行上述代碼,將輸出:
Function name:
這是因?yàn)樵谡{(diào)用my_function時(shí),實(shí)際上是在全局作用域中調(diào)用的,所以返回的是模塊名,如果要在特定函數(shù)內(nèi)部獲取該函數(shù)的名稱,可以將上述代碼放入該函數(shù)內(nèi)部。
網(wǎng)站名稱:python如何獲取函數(shù)名
本文網(wǎng)址:http://m.fisionsoft.com.cn/article/dpseepe.html


咨詢
建站咨詢
