標籤:alt ons url print 方法 logo 內建函數 技術 函數
反射
反射的作用:反射得作用是提高代碼可讀行。
__import__匯入模組和import匯入模組的區別:
__import__匯入模組是通過字串進行匯入。import是常用得匯入模組方法。
反射常用到得4個內建函數分別為:getattr、hasattr、setattr、delattr 擷取成員、檢查成員、設定成員、刪除成員。
執行個體:
最初模組調用是這樣得:
# commons.pydef login(): print(‘炫酷的登入頁面‘)def logout(): print(‘炫酷的退出頁面‘)def home(): print(‘炫酷的首頁面‘)# index.pyimport commonsdef run(): inp = input(‘請輸入要訪問的url:‘) if inp == ‘login‘: commons.login() elif inp == ‘logout‘: commons.logout() elif inp == ‘home‘: commons.home() else: print(‘404‘)
用了反射後是這樣得:
#commons.pydef login(): print(‘炫酷的登入頁面‘)def logout(): print(‘炫酷的退出頁面‘)def home(): print(‘炫酷的首頁面‘)#index.pyimport commonsdef run(): inp = input(‘請輸入要訪問的url:‘) # inp字串類型 inp = "login" # 利用字串的形式去對象(模組)中操作(尋找/檢查/刪除/設定)成員# delattr()# setattr() if hasattr(commons, inp): func = getattr(commons,inp) func() else: print(‘404‘)if __name__ == ‘__main__‘: run()
模組也可以通過字串進行匯入:
def run(): # account/login inp = input(‘請輸入要訪問的url:‘) # inp字串類型 inp = "login" # 利用字串的形式去對象(模組)中操作(尋找/檢查/刪除/設定)成員 # delattr() # setattr() m, f = inp.split(‘/‘) obj = __import__(m) if hasattr(obj, f): func = getattr(obj,f) func() else: print(‘404‘)if __name__ == ‘__main__‘: run()
對於反射小節:
1、根據字串的形式匯入模組。2、根據字串的形式去對象(某個模組)中操作其成員。
Python開發【第一篇】Python基礎之反射