最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python通過getattr函數(shù)獲取對象的屬性值

 更新時(shí)間:2020年10月16日 09:31:45   作者:lincappu  
這篇文章主要介紹了Python通過getattr函數(shù)獲取對象的屬性值,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

英文文檔:

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. 函數(shù)功能是從對象object中獲取名稱為name的屬性,等效與調(diào)用object.name。

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

    
>>> s = Stduent('Aim')
>>> getattr(s,'name') #等效于調(diào)用s.name
'Aim'
>>> s.name
'Aim'

  2. 函數(shù)第三個(gè)參數(shù)default為可選參數(shù),如果object中含義name屬性,則返回name屬性的值,如果沒有name屬性,則返回default值,如果default未傳入值,則報(bào)錯(cuò)。

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

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

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

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

與__getattr__的區(qū)別:

__getattr__是類的內(nèi)置方法,當(dāng)找不到某個(gè)屬性時(shí)會(huì)調(diào)用該方法;找到就不會(huì)調(diào)用.

getattr與類無關(guān).

一個(gè)例子:作為data的代理類,可以以這種方式來使用data的屬性.

class DataProxy(...):
  def __getattr__(self, item):
    return getattr(self.data, item)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

蕲春县| 巴彦县| 资溪县| 蒲江县| 美姑县| 合山市| 昌都县| 湘阴县| 福安市| 阳新县| 郑州市| 河西区| 巩留县| 济源市| 瑞安市| 成安县| 临澧县| 定兴县| 临桂县| 海林市| 青河县| 仙居县| 通海县| 定兴县| 闽清县| 正蓝旗| 临清市| 永登县| 平泉县| 全南县| 北流市| 三原县| 孟连| 呼和浩特市| 镇康县| 井陉县| 鄯善县| 西乡县| 汝南县| 醴陵市| 青州市|