python反射機(jī)制內(nèi)置函數(shù)及場(chǎng)景構(gòu)造詳解
反射的優(yōu)點(diǎn)
它的核心本質(zhì)其實(shí)就是基于字符串的事件驅(qū)動(dòng),通過(guò)字符串的形式去操作對(duì)象的屬性或者方法
一個(gè)概念被提出來(lái),就是要明白它的優(yōu)點(diǎn)有哪些,這樣我們才能知道為什么要使用反射。
場(chǎng)景構(gòu)造
開(kāi)發(fā)1個(gè)網(wǎng)站,由兩個(gè)文件組成,一個(gè)是具體執(zhí)行操作的文件commons.py
,一個(gè)是入口文件visit.py
需求:需要在入口文件中設(shè)置讓用戶輸入url, 根據(jù)用戶輸入的url去執(zhí)行相應(yīng)的操作
# commons.py def login(): print("這是一個(gè)登陸頁(yè)面!") def logout(): print("這是一個(gè)退出頁(yè)面!") def home(): print("這是網(wǎng)站主頁(yè)面!")
# visit.py import commons def run(): inp = input("請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: ").strip() if inp == 'login': commons.login() elif inp == 'logout': commons.logout() elif inp == 'index': commons.home() else: print('404') if __name__ == '__main__': run()
運(yùn)行run
方法后,結(jié)果如下:
請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: login
這是一個(gè)登陸頁(yè)面!
提問(wèn):上面使用if判斷,根據(jù)每一個(gè)url請(qǐng)求去執(zhí)行指定的函數(shù),若commons.py
中有100個(gè)操作,再使用if判斷就不合適了回答:使用python反射機(jī)制,commons.py
文件內(nèi)容不變,修改visit.py文件,內(nèi)容如下
import commons def run(): inp = input("請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: ").strip() if hasattr(commons, inp): getattr(commons, inp)() else: print("404") if __name__ == '__main__': run()
使用這幾行代碼,可以應(yīng)對(duì)commons.py
文件中任意多個(gè)頁(yè)面函數(shù)的調(diào)用!
反射中的內(nèi)置函數(shù)
getattr
def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass
getattr()
函數(shù)的第一個(gè)參數(shù)需要是個(gè)對(duì)象,上面的例子中,我導(dǎo)入了自定義的commons
模塊,commons就是個(gè)對(duì)象;第二個(gè)參數(shù)是指定前面對(duì)象中的一個(gè)方法名稱。
getattr(x, 'y')
等價(jià)于執(zhí)行了x.y
。假如第二個(gè)參數(shù)輸入了前面對(duì)象中不存在的方法,該函數(shù)會(huì)拋出異常并退出。所以這個(gè)時(shí)候,為了程序的健壯性,我們需要先判斷一下該對(duì)象中有沒(méi)有這個(gè)方法,于是用到了hasattr()
函數(shù)
hasattr
def hasattr(*args, **kwargs): # real signature unknown """ Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. """ pass
hasattr()
函數(shù)返回對(duì)象是否擁有指定名稱的屬性,簡(jiǎn)單的說(shuō)就是檢查在第一個(gè)參數(shù)的對(duì)象中,能否找到與第二參數(shù)名相同的方法。源碼的解釋還說(shuō),該函數(shù)的實(shí)現(xiàn)其實(shí)就是調(diào)用了getattr()
函數(shù),只不過(guò)它捕獲了異常而已。所以通過(guò)這個(gè)函數(shù),我們可以先去判斷對(duì)象中有沒(méi)有這個(gè)方法,有則使用getattr()
來(lái)獲取該方法。
setattr
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v'' """ pass
setattr()
函數(shù)用來(lái)給指定對(duì)象中的方法重新賦值(將新的函數(shù)體/方法體賦值給指定的對(duì)象名)僅在本次程序運(yùn)行的內(nèi)存中生效。setattr(x, 'y', v)
等價(jià)于x.y = v
delattr
def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """ pass
刪除指定對(duì)象中的指定方法,特別提示:只是在本次運(yùn)行程序的內(nèi)存中將該方法刪除,并沒(méi)有影響到文件的內(nèi)容
__import__模塊反射
接著上面網(wǎng)站的例子,現(xiàn)在一個(gè)后臺(tái)文件已經(jīng)不能滿足我的需求,這個(gè)時(shí)候需要根據(jù)職能劃分后臺(tái)文件,現(xiàn)在我又新增了一個(gè)user.py
這個(gè)用戶類(lèi)的文件,也需要導(dǎo)入到首頁(yè)以備調(diào)用。
但是,上面網(wǎng)站的例子,我已經(jīng)寫(xiě)死了只能指定commons
模塊的方法任意調(diào)用,現(xiàn)在新增了user
模塊,那此時(shí)我又要使用if判斷?
答:不用,使用Python自帶的函數(shù)__import__
由于模塊的導(dǎo)入也需要使用Python反射的特性,所以模塊名也要加入到url中,所以現(xiàn)在url請(qǐng)求變成了類(lèi)似于commons/visit
的形式
# user.py def add_user(): print('添加用戶') def del_user(): print('刪除用戶')
# commons.py def login(): print("這是一個(gè)登陸頁(yè)面!") def logout(): print("這是一個(gè)退出頁(yè)面!") def home(): print("這是網(wǎng)站主頁(yè)面!")
# visit.py def run(): inp = input("請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: ").strip() # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法 modules, func = inp.split('/') obj_module = __import__(modules) if hasattr(obj_module, func): getattr(obj_module, func)() else: print("404") if __name__ == '__main__': run()
最后執(zhí)行run
函數(shù),結(jié)果如下:
請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: user/add_user
添加用戶
請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: user/del_user
刪除用戶
現(xiàn)在我們就能體會(huì)到__import__
的作用了,就是把字符串當(dāng)做模塊去導(dǎo)入。
但是如果我的網(wǎng)站結(jié)構(gòu)變成下面的
|- visit.py |- commons.py |- user.py |- lib |- __init__.py |- connectdb.py
現(xiàn)在我想在visit
頁(yè)面中調(diào)用lib
包下connectdb
模塊中的方法,還是用之前的方式調(diào)用可以嗎?
# connectdb.py def conn(): print("已連接mysql")
# visit.py def run(): inp = input("請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: ").strip() # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法 modules, func = inp.split('/') obj_module = __import__('lib.' + modules) if hasattr(obj_module, func): getattr(obj_module, func)() else: print("404") if __name__ == '__main__': run()
運(yùn)行run
命令,結(jié)果如下:
請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: connectdb/conn
404
結(jié)果顯示找不到,為了測(cè)試調(diào)用lib下的模塊,我拋棄了對(duì)所有同級(jí)目錄模塊的支持,所以我們需要查看__import__
源碼
def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__ """ __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module Import a module. Because this function is meant for use by the Python interpreter and not for general use, it is better to use importlib.import_module() to programmatically import a module. The globals argument is only used to determine the context; they are not modified. The locals argument is unused. The fromlist should be a list of names to emulate ``from name import ...'', or an empty list to emulate ``import name''. When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty. The level argument is used to determine whether to perform absolute or relative imports: 0 is absolute, while a positive number is the number of parent directories to search relative to the current module. """ pass
__import__
函數(shù)中有一個(gè)fromlist
參數(shù),源碼解釋說(shuō),如果在一個(gè)包中導(dǎo)入一個(gè)模塊,這個(gè)參數(shù)如果為空,則return這個(gè)包對(duì)象,如果這個(gè)參數(shù)不為空,則返回包下面指定的模塊對(duì)象,所以我們上面是返回了包對(duì)象,所以會(huì)返回404的結(jié)果,現(xiàn)在修改如下:
# visit.py def run(): inp = input("請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: ").strip() # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法 modules, func = inp.split('/') # 只新增了fromlist=True obj_module = __import__('lib.' + modules, fromlist=True) if hasattr(obj_module, func): getattr(obj_module, func)() else: print("404") if __name__ == '__main__': run()
運(yùn)行run方法,結(jié)果如下:
請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: connectdb/conn
已連接mysql
成功了,但是我寫(xiě)死了lib前綴
,相當(dāng)于拋棄了commons
和user
兩個(gè)導(dǎo)入的功能,所以以上代碼并不完善,需求復(fù)雜后,還是需要對(duì)請(qǐng)求的url做一下判斷
def getf(module, func): """ 抽出公共部分 """ if hasattr(module, func): func = getattr(module, func) func() else: print('404') def run(): inp = input("請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: ").strip() if len(inp.split('/')) == 2: # modules代表導(dǎo)入的模塊,func代表導(dǎo)入模塊里面的方法 modules, func = inp.split('/') obj_module = __import__(modules) getf(obj_module, func) elif len(inp.split("/")) == 3: p, module, func = inp.split('/') obj_module = __import__(p + '.' + module, fromlist=True) getf(obj_module, func) if __name__ == '__main__': run()
運(yùn)行run函數(shù),結(jié)果如下:
請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: lib/connectdb/conn
已連接mysql
請(qǐng)輸入您想訪問(wèn)頁(yè)面的url: user/add_user
添加用戶
當(dāng)然你也可以繼續(xù)優(yōu)化代碼,現(xiàn)在只判斷了有1個(gè)斜杠和2個(gè)斜杠的,如果目錄層級(jí)更多呢,這個(gè)暫時(shí)不考慮,本次是為了了解python的反射機(jī)制
以上就是python反射機(jī)制內(nèi)置函數(shù)及場(chǎng)景構(gòu)造詳解的詳細(xì)內(nèi)容,更多關(guān)于python反射機(jī)制內(nèi)置函數(shù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
對(duì)python中各個(gè)response的使用說(shuō)明
今天小編就為大家分享一篇對(duì)python中各個(gè)response的使用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-03-03Python實(shí)現(xiàn)識(shí)別花卉種類(lèi)的示例代碼
“無(wú)窮小亮的科普日常”經(jīng)常會(huì)發(fā)布一些鑒定網(wǎng)絡(luò)熱門(mén)生物視頻,既科普了生物知識(shí),又滿足觀眾們的獵奇心理。今天我們也來(lái)用Python鑒定一下網(wǎng)絡(luò)熱門(mén)植物2022-04-04淺談tensorflow使用張量時(shí)的一些注意點(diǎn)tf.concat,tf.reshape,tf.stack
這篇文章主要介紹了淺談tensorflow使用張量時(shí)的一些注意點(diǎn)tf.concat,tf.reshape,tf.stack,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06python中time tzset()函數(shù)實(shí)例用法
在本篇文章里小編給大家整理的是一篇關(guān)于python中time tzset()函數(shù)實(shí)例用法內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-02-02Python基于whois模塊簡(jiǎn)單識(shí)別網(wǎng)站域名及所有者的方法
這篇文章主要介紹了Python基于whois模塊簡(jiǎn)單識(shí)別網(wǎng)站域名及所有者的方法,簡(jiǎn)單分析了Python whois模塊的安裝及使用相關(guān)操作技巧,需要的朋友可以參考下2018-04-04關(guān)于python的mmh3庫(kù)安裝以及使用詳解
這篇文章主要介紹了關(guān)于python的mmh3庫(kù)安裝以及使用詳解,哈希方法主要有MD、SHA、Murmur、CityHash、MAC等幾種方法,mmh3全程murmurhash3,是一種非加密的哈希算法,常用于hadoop等分布式存儲(chǔ)情境中,需要的朋友可以參考下2023-07-07jupyter notebook使用argparse傳入list參數(shù)
這篇文章主要介紹了jupyter notebook使用argparse傳入list參數(shù),jupyter notebook其實(shí)是可以使用 argparse來(lái)調(diào)用參數(shù)的,只要把參數(shù)轉(zhuǎn)為list即可,下面來(lái)看看具體的實(shí)現(xiàn)過(guò)程吧2022-01-01在Python中居然可以定義兩個(gè)同名通參數(shù)的函數(shù)
今天小編就為大家分享一篇在Python中居然可以定義兩個(gè)同名通參數(shù)的函數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01Python編程深度學(xué)習(xí)繪圖庫(kù)之matplotlib
今天小編就為大家分享一篇關(guān)于Python編程深度學(xué)習(xí)繪圖庫(kù)之matplotlib,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12