Python開發【第一篇】Python基礎之反射

來源:互聯網
上載者:User

標籤: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基礎之反射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.