Python(Built-in Functions)之getattr()

Python(Built-in Functions)之getattr()

  • Python編程語言官方給出的Api文檔解釋是:
    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.

描述

  • getattr()函數用於返回一個對象屬性值。

語法:

getattr(object, name[, default])

參數說明:

  • object: 對象;
  • name: 必須爲字符串,對象屬性;
  • default: 默認返回值,如果不提供該參數,在沒有對象屬性(也就是name)時,將觸發AttributeError。

返回值:

  • 返回對象屬性值

實例說明:

>>> class Test(object): # Test對象
...     a = 1
...
>>> test = Test() 
>>> getattr(test, 'a') # 獲取屬性a的值,返回值爲1
1
>>> getattr(test, 'a', 2) # 如果存在屬性a的值,返回值是屬性a的值,默認值設置無效
1
>>> getattr(test, 'b') # 獲取屬性b的值, 返回AttributeError,因爲不存在屬性b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'b'
>>> getattr(test, 'c', 3) # 屬性c的值不存在,但是設置了默認值
3
>>> getattr(test, 'c') # 默認值並不是屬性c的值,請記住屬性c的值不存在,返回AttributeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'c'
>>>

測試用例注意:
...後面是一個Tab鍵長度,第二個...直接點擊Enter即可。其他的跟着操作即可

  • 所以在很多情況下爲了不出現AttributeError的錯誤信息,需要加上默認值設置來避免AttributeError的錯誤出現。

額外知識:

  • Build-in Functions指的是Python編程語言的內置函數,什麼是內置函數了?
  • 官方給出的解釋是:

The Python interpreter has a number of functions and types built into it that are always available.

  • Python解釋器內置了許多始終可用的函數和類型。換句話說,getattr()始終是可以用的。

JackDan Thinking

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章