這篇文章將為大家詳細(xì)講解有關(guān)Python中如何使用getattr()函數(shù),小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
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-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:/腳本項(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
本文名稱:Python中如何使用getattr()函數(shù)-創(chuàng)新互聯(lián)
標(biāo)題來(lái)源:http://vcdvsql.cn/article42/djghhc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、網(wǎng)頁(yè)設(shè)計(jì)公司、App開發(fā)、品牌網(wǎng)站設(shè)計(jì)、定制網(wǎng)站、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容