python中getattr()的用法


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

 

而第二種可以訪問所有帶下划線的屬性

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM