Python getattr()函數(shù)使用方法代碼實例
getatter()通過方法名字符串調(diào)用方法,這個方法最主要的作用就是實現(xiàn)反射機(jī)制,也就是說可以通過字符串獲取方法實例,這樣就可以把一個類可能要調(diào)用的方法放到配置文件里,需要的時候進(jìn)行動態(tài)加載。
1: 可以從類中獲取屬性和函數(shù)
新建test.py文件,代碼如下:
# encoding:utf-8 import sys class GetText(): def __init__(self): pass @staticmethod def A(): print("this is a staticmethod function") def B(self): print("this is a func") c = "cc desc" if __name__ == '__main__': print(sys.modules[__name__]) # <module '__main__' from 'D:/腳本項目/lianxi/clazz/test.py'> print(GetText) # <class '__main__.GetText'> # 獲取函數(shù) print(getattr(GetText, "A")) # <function GetText.A at 0x00000283C2B75798> # 獲取函數(shù)返回值 getattr(GetText, "A")() # this is a staticmethod function getattr(GetText(), "A")() # this is a staticmethod function print(getattr(GetText, "B")) # <function GetText.B at 0x000001371BF55798> # 非靜態(tài)方法不可用 # getattr(GetText, "B")() getattr(GetText(), "B")() # this is a func print(getattr(GetText, "c")) # cc desc print(getattr(GetText(), "c")) # cc desc
2:從模塊中獲取類(通過類名字符串得到類對象)
新建test1.py,代碼如下:
#encoding:utf-8 import sys import test print(sys.modules[__name__]) # 從模塊中獲取類對象 class_name = getattr(test, "GetText") print(class_name) # <class 'test.GetText'> # 調(diào)用類的屬性和函數(shù) print(getattr(class_name, "A")) # <function GetText.A at 0x000001D637365678> # 獲取函數(shù)返回值 getattr(class_name, "A")() # this is a staticmethod function getattr(class_name(), "A")() # this is a staticmethod function print(getattr(class_name(), "B")) # <bound method GetText.B of <test.GetText object at 0x0000022D3B9EE348>> # getattr(class_name, "B")() 非靜態(tài)方法不可用 getattr(class_name(), "B")() # this is a func # 獲取屬性值 print(getattr(class_name, "c")) # cc desc print(getattr(class_name(), "c")) # cc desc
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Django事務(wù)transaction的使用以及多個裝飾器問題
這篇文章主要介紹了Django事務(wù)transaction的使用以及多個裝飾器問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08python?包實現(xiàn)JSON?輕量數(shù)據(jù)操作
這篇文章主要介紹了python?包實現(xiàn)JSON?輕量數(shù)據(jù)操作,文章介紹內(nèi)容首先將對象轉(zhuǎn)為json字符串展開主題詳細(xì)內(nèi)容需要的小伙伴可以參考一下2022-04-04python消費(fèi)kafka數(shù)據(jù)批量插入到es的方法
今天小編就為大家分享一篇python消費(fèi)kafka數(shù)據(jù)批量插入到es的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12python實現(xiàn)處理Excel表格超詳細(xì)系列
這篇文章主要介紹了python實現(xiàn)處理Excel表格超詳細(xì)系列,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08解讀調(diào)用jupyter?notebook文件內(nèi)的函數(shù)一種簡單方法
這篇文章主要介紹了解讀調(diào)用jupyter?notebook文件內(nèi)的函數(shù)一種簡單方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01