Python的反射

來源:互聯網
上載者:User

標籤:djang   __name__   UNC   coding   概念   參數   引入   else   self   

什麼是反射

反射是一個很重要的概念,它可以把字串映射到執行個體的變數或者執行個體的方法然後可以去執行調用、修改等操作。它有三個重要的方法:

  • getattr
  • setattr
  • hasattr

反射常常用在動態載入模組的情境中。

#!/usr/bin/env python# -*- coding: utf-8 -*-# Author: rex.cheny# E-mail: [email protected]class TestObj(object):    def __init__(self, name, age):        self.name = name        self.age = age    def displayName(self):        print("displayName方法執行,列印姓名:", self.name)def AAA(self):    print("I am AAA.")def main():    to = TestObj("Tom", 23)    # 查看 to 執行個體裡面是否有 name 這個屬性    if hasattr(to, "name"):        print("執行個體 to 中有 name 屬性。")        print(getattr(to, "name"))    else:        print("執行個體 to 中沒有 name 屬性。")    if hasattr(to, "displayName"):        print("執行個體 to 中有 displayName 屬性。")        getattr(to, "displayName")()    else:        print("執行個體 to 中沒有 displayName 屬性。")    if hasattr(to, "AAA"):        print("執行個體 to 中有 AAA 屬性。")        getattr(to, "AAA")()    else:        print("執行個體 to 中沒有 AAA 屬性,將會設定。")        setattr(to, "AAA", AAA)  # 參數:執行個體、方法名稱、具體方法        # to.AAA(to)  # 這裡一定要主動傳遞一個執行個體進去,因為它不會自動裝配self        getattr(to, "AAA")(to)if __name__ == ‘__main__‘:    main()

AAA是動態裝載到執行個體裡面去的。

反射使用通過字串匯入模組
#!/usr/bin/env python# -*- coding: utf-8 -*-# Author: rex.cheny# E-mail: [email protected]temp = "re"model = __import__(temp)def main():    txt = "hj123uo"    pattern = model.compile(r"[0-9]+")    print(model.search(pattern, txt).group())if __name__ == ‘__main__‘:    main()

以字串的形式使用模組的方法
#!/usr/bin/env python# -*- coding: utf-8 -*-# Author: rex.cheny# E-mail: [email protected] temp = "re"  # 要引入的模組func = "compile"  # 要使用的方法model = __import__(temp)  # 匯入模組function = getattr(model, func)  # 找到模組中的屬性def main():    txt = "hj123uo"    pattern = function(r"[0-9]+")  # 這裡執行funcation()就等於執行re.compile()函數    print(model.search(pattern, txt).group())if __name__ == ‘__main__‘:    main()

反射到底有什麼用?

上面使用re.compile()函數的整個過程看起來很麻煩,但是你要知道這就等於實現了動態載入和執行所需要的模組或方法而不需要全部寫入到PY檔案中,當然具體需要執行的方法你也要提前實現。典型的使用情境就是web的URL路由。目前所有的web架構的URL路由基本都是這個原理。
使用者輸入不同的URL如何載入不同的PY檔案以及調用裡面的方法呢?你想一想Django裡面,它並不是這樣的,它依然需要你設定URL以及該URL對應的PY檔案,為什嗎?因為這樣調試方便,當然你能力足夠也可以給它改寫成反射的機制。

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.