英文文件:
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 equid thexisx fbar. 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,但提供了默认值,返回默认值 >>> 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'
以上是Python內建getattr函數的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!