反射
1、定義:通過字串映射或者修改程式運行時的狀態、屬性和方法,反射的作用是實作動態的記憶體裝配
2、hasattr(obj,name_str) , 判斷一個物件obj里是否有對應的name_str字串的方法
3、getattr(obj,name_str):根據字串去獲取obj物件里的對應的方法的記憶體地址
4、setattr(obj,'y',z):設定物件的方法或者屬性,相當于 "x.y = v'',V為方法名或者屬性值
5、delattr(obj,name_str):洗掉一個物件的屬性或者方法
6、動態呼叫類,代碼如下:
def talk(self): print("%s is yelling...." % self.name) class Dog(object): def __init__(self, name): self.name = name def eat(self, food): print("%s is eating..." % self.name, food) d = Dog("NiuHanYang") choice = input(">>:").strip() if hasattr(d, choice): getattr(d, choice)("包子") else: # 相當于d.talk = bulk setattr(d, choice, talk) func = getattr(d, choice) func(d)
7、動態匯入類,此類放在lib目錄下,代碼如下:
class Test(object): def __init__(self): self.name = "tangwei" def eat(self): print("I started eating...")
匯入代碼如下:
# 動態匯入類 # 匯入方法一:使用__import__僅匯入了模塊所在目錄 lib = __import__("lib.test_import") lib.test_import.Test().eat() # 匯入方法二:推薦用這種,可以直接匯入模塊 import importlib test_import = importlib.import_module("lib.test_import") test_import.Test().eat()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/149346.html
標籤:Python
