標籤:djang __name__ UNC coding 概念 參數 引入 else self
什麼是反射
反射是一個很重要的概念,它可以把字串映射到執行個體的變數或者執行個體的方法然後可以去執行調用、修改等操作。它有三個重要的方法:
反射常常用在動態載入模組的情境中。
#!/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的反射