Python內置函數(25)——getattr


英文文檔:

getattr (object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
說明:
  
  1. 函數功能是從對象object中獲取名稱為name的屬性,等效與調用object.name。
#定義類Student
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> s = Stduent('Aim')
>>> getattr(s,'name') #等效於調用s.name
'Aim'
>>> s.name
'Aim'

  2. 函數第三個參數default為可選參數,如果object中含義name屬性,則返回name屬性的值,如果沒有name屬性,則返回default值,如果default未傳入值,則報錯。

#定義類Student
>>> class Student:
    def __init__(self,name):
        self.name = name

>>> getattr(s,'name') #存在屬性name
'Aim'

>>> getattr(s,'age',6) #不存在屬性age,但提供了默認值,返回默認值
6

>>> getattr(s,'age') #不存在屬性age,未提供默認值,調用報錯
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'

 


免責聲明!

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



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