pyhon反射
- 2022 年 3 月 22 日
- 筆記
一:反射
1.python面向對象中的反射:
通過字元串的形式操作對象相關的屬性。python中的一切事物都是對象(都可以使用反射)
2.四個內置方法
hasattr 檢測是否含有某屬性
getattr 獲取屬性
setattr 設置屬性
delattr 刪除屬性
3.四個方法適用於類和對象(一切皆對象,類本身也是對象)
class People:
country = “china”
def init(self,name,age):
self.name = name
self.age = age
def tell_info(self):
print(self.name,self.age)
obj = People(‘egon’,18)
二:hasattr 檢測是否含有某屬性
1.判斷obj這個對象有沒有country這個屬性
print(hasattr(obj,”country”)) # obj.country 也可以說obj能不能點出.country
三:getattr 獲取屬性
1.通過字元串country獲取屬性
res = getattr(obj,’country’) # china 拿到屬性值
print(res)
2.通過字元串tell_info獲取綁定方法
res = getattr(obj,’tell_info’)
print(res)
3.調method方法獲取到的是obj的資訊
method = getattr(obj,’tell_info’)
metsetattrhod()
四:setattr 設置屬性
1.通過字元串xxx賦給新的屬性值
setattr(obj,”xxx”,1111) # 等同於obj.xxx = 1111
print(obj.xxx)
五:delattr 刪除屬性
delattr(obj,”name”)
print(obj.name)