av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁技術文章
文章詳情頁

Python getattr()函數使用方法代碼實例

瀏覽:8日期:2022-07-14 14:59:51

getatter()通過方法名字符串調用方法,這個方法最主要的作用就是實現反射機制,也就是說可以通過字符串獲取方法實例,這樣就可以把一個類可能要調用的方法放到配置文件里,需要的時候進行動態加載。

1: 可以從類中獲取屬性和函數

新建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:/腳本項目/lianxi/clazz/test.py’> print(GetText) # <class ’__main__.GetText’> # 獲取函數 print(getattr(GetText, 'A')) # <function GetText.A at 0x00000283C2B75798> # 獲取函數返回值 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> # 非靜態方法不可用 # 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-8import sysimport testprint(sys.modules[__name__]) # 從模塊中獲取類對象class_name = getattr(test, 'GetText')print(class_name) # <class ’test.GetText’> # 調用類的屬性和函數print(getattr(class_name, 'A')) # <function GetText.A at 0x000001D637365678># 獲取函數返回值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')() 非靜態方法不可用getattr(class_name(), 'B')() # this is a func # 獲取屬性值print(getattr(class_name, 'c')) # cc descprint(getattr(class_name(), 'c')) # cc desc

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: av网站在线免费观看 | 免费观看一级黄色录像 | 国产精品视频免费观看 | 欧美日韩视频一区二区 | 午夜av在线 | 国产精品久久久久久久久免费 | 亚洲精品乱码久久久久久蜜桃91 | 欧美日韩视频 | 亚洲精品1区 | 精品在线观看一区 | www国产成人| 免费观看羞羞视频网站 | 久久久久国产一区二区三区四区 | 日韩免费一二三区 | 色先锋影音 | 亚洲人成人一区二区在线观看 | 国产成人精品视频在线观看 | 日日摸夜夜爽人人添av | 国产视频亚洲视频 | 黄色精品 | 中文字幕日本一区二区 | 99国产精品久久久久久久 | 一区中文字幕 | 情侣酒店偷拍一区二区在线播放 | 国产在线精品一区二区 | 你懂的免费在线 | 2019天天操 | 黄色免费av | 国产精品亚洲欧美日韩一区在线 | 日韩欧美一区二区三区免费观看 | 久久国产精品视频 | 日日操日日舔 | gav成人免费播放视频 | 一区二区视频免费观看 | 久久福利网站 | 男女网站视频 | 国产视频在线观看一区二区三区 | 91九色婷婷 | 久久精品网 | 五月综合激情婷婷 | 一区二区精品视频 |