Python getattr()函數(shù)使用方法代碼實(shí)例
getatter()通過(guò)方法名字符串調(diào)用方法,這個(gè)方法最主要的作用就是實(shí)現(xiàn)反射機(jī)制,也就是說(shuō)可以通過(guò)字符串獲取方法實(shí)例,這樣就可以把一個(gè)類可能要調(diào)用的方法放到配置文件里,需要的時(shí)候進(jìn)行動(dòng)態(tài)加載。
1: 可以從類中獲取屬性和函數(shù)
新建test.py文件,代碼如下:
# encoding:utf-8import 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:/腳本項(xiàng)目/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:從模塊中獲取類(通過(guò)類名字符串得到類對(duì)象)
新建test1.py,代碼如下:
#encoding:utf-8import sysimport testprint(sys.modules[__name__]) # 從模塊中獲取類對(duì)象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 functiongetattr(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 descprint(getattr(class_name(), 'c')) # cc desc
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. asp取整數(shù)mod 有小數(shù)的就自動(dòng)加12. 詳解瀏覽器的緩存機(jī)制3. CSS3中Transition屬性詳解以及示例分享4. 詳解盒子端CSS動(dòng)畫(huà)性能提升5. 利用CSS制作3D動(dòng)畫(huà)6. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?7. CSS hack用法案例詳解8. 怎樣打開(kāi)XML文件?xml文件如何打開(kāi)?9. css代碼優(yōu)化的12個(gè)技巧10. XML入門(mén)的常見(jiàn)問(wèn)題(二)
