Python中的getattr、__getattr__、__getattribute__、__get__詳解
getattr
getattr(object, name[, default])
是Python的內(nèi)置函數(shù)之一,它的作用是獲取對象的屬性。
示例
>>> class Foo: ... def __init__(self, x): ... self.x = x ... >>> f = Foo(10) >>> getattr(f, 'x') 10 >>> f.x 10 >>> getattr(f, 'y', 'bar') 'bar'
__getattr__
object.__getattr__(self, name)
是一個對象方法,當(dāng)找不到對象的屬性時會調(diào)用這個方法。
示例
>>> class Frob: ... def __init__(self, bamf): ... self.bamf = bamf ... def __getattr__(self, name): ... return 'Frob does not have `{}` attribute.'.format(str(name)) ... >>> f = Frob("bamf") >>> f.bar 'Frob does not have `bar` attribute.' >>> f.bamf 'bamf'
getattribute
object.__getattribute__(self, name)
是一個對象方法,當(dāng)訪問某個對象的屬性時,會無條件的調(diào)用這個方法。該方法應(yīng)該返回屬性值或者拋出AttributeError
異常。
示例
>>> class Frob(object): ... def __getattribute__(self, name): ... print "getting `{}`".format(str(name)) ... return object.__getattribute__(self, name) ... >>> f = Frob() >>> f.bamf = 10 >>> f.bamf getting `bamf` 10
get
__get__()
方法是描述器方法之一。描述器用于將訪問對象屬性轉(zhuǎn)變成調(diào)用描述器方法。
示例
>>> class Descriptor(object): ... def __get__(self, obj, objtype): ... print("get value={}".format(self.val)) ... return self.val ... def __set__(self, obj, val): ... print("set value={}".format(val)) ... self.val = val ... >>> class Student(object): ... age = Descriptor() ... >>> s = Student() >>> s.age = 12 set value=12 >>> print(s.age) get value=12 12
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Python實現(xiàn)的下載網(wǎng)頁源碼功能示例
這篇文章主要介紹了Python實現(xiàn)的下載網(wǎng)頁源碼功能,涉及Python基于http請求與響應(yīng)實現(xiàn)的網(wǎng)頁源碼讀取功能相關(guān)操作技巧,需要的朋友可以參考下2017-06-06在IIS服務(wù)器上以CGI方式運行Python腳本的教程
這篇文章主要介紹了在IIS服務(wù)器上以CGI方式運行Python腳本的教程,雖然IIS的性能并不理想...需要的朋友可以參考下2015-04-04在 Jupyter 中重新導(dǎo)入特定的 Python 文件(場景分析)
Jupyter 是數(shù)據(jù)分析領(lǐng)域非常有名的開發(fā)環(huán)境,使用 Jupyter 寫數(shù)據(jù)分析相關(guān)的代碼會大大節(jié)約開發(fā)時間。這篇文章主要介紹了在 Jupyter 中如何重新導(dǎo)入特定的 Python 文件,需要的朋友可以參考下2019-10-10