1.getattr() 是python 中的一個內置函數,用來獲取對象中的屬性值
2.getattr(obj,name[,default]) 其中obj為對象名,name是對象中的屬性,必須為字符串。
3.兩種表達式的區別
第一種,getattr(obj,"_attr")
第二種,getattr(obj,"_" + attr)
第一種只能訪問_attr屬性,
class Student: # 定義類 def __init__(self,name,identity,age): self._name = name self._identity = identity self.age = age def __getitem__(self,item): if isinstance(item,str): return getattr(self,"_item")
# 實例化一個學生類對象 st = Student("Apollo", 15618661616, 28)
''' 執行: print(st["age"]) 打印: Traceback (most recent call last): File "E:/Python學習/xfz/xfzapp/tests.py", line 13, in <module> print(st["age"]) File "E:/Python學習/xfz/xfzapp/tests.py", line 9, in __getitem__ return getattr(self, "_item") AttributeError: 'Student' object has no attribute '_item' '''
''' print(st["name"]) Traceback (most recent call last): File "E:/Python學習/xfz/xfzapp/tests.py", line 26, in <module> print(st["name"]) File "E:/Python學習/xfz/xfzapp/tests.py", line 9, in __getitem__ return getattr(self, "_item") AttributeError: 'Student' object has no attribute '_item' '''
第二種可以訪問所有帶下划線的屬性
''' 執行: print(st["age"]) 打印: Traceback (most recent call last): File "E:/Python學習/xfz/xfzapp/tests.py", line 13, in <module> print(st["age"]) File "E:/Python學習/xfz/xfzapp/tests.py", line 9, in __getitem__ return getattr(self,"_" + item) AttributeError: 'Student' object has no attribute '_age' '''
print(st["name"]) # Apollo