python3,定制類,getattr相關(guān)用法
問題描述
class Chain(object): def __init__(self,path=''):self._path = path def __getattr__(self,path):return Chain('%s/%s' %(self._path,path)) def __call__(self,path):return Chain('%s/%s' %(self._path,path)) def __str__(self):return self._path __repr__ = __str__ print(Chain().a.b.user('Michael').c.d)
看了好久還是理解不了這語句,如能詳述一些細節(jié),感激不盡
問題解答
回答1:getattr(object, name[, default])
class Student(object): def __init__(self):self.name = ’Michael’ def __getattr__(self,attr):return attrs = Student()s.name --> ’Michael’s.score--> ’score’
_getattr__是python里的一個內(nèi)建函數(shù),動態(tài)返回一個屬性當調(diào)用不存在的屬性時,Python會試圖調(diào)用__getattr__(self,’score’)來獲取屬性,并且返回score
__str__用于打印函數(shù)__call__把類當做類似函數(shù)一樣調(diào)用
代碼執(zhí)行流程: Chain()創(chuàng)建一個實例,并且 path初始默認為 '' ,Chain().a 時,類中并沒有 a 屬性,Python解析器調(diào)用 getattr函數(shù) --> __getattr__(self,path=’a’),并返回一個Chain實例,然后把/a 賦值gei path 傳入,繼續(xù)b,因為同樣沒有b 屬性,執(zhí)行g(shù)etattr函數(shù),將/a/b傳入,然后.user(“Michael”),先會執(zhí)行g(shù)etattr返回Chain實例,但是因為有()括號在,所以返回的是Chain(),這個就會調(diào)用call函數(shù)了,然后把“ChenTian”作為path傳入,然后call函數(shù)就返回了/a/b/user/ChenTian,剩下的類同。
.user('Michael”) 剛開始的user被getattr函數(shù)捕獲,并返回Chain(),然后再執(zhí)行__call__來調(diào)用 'Michael'
代碼流程圖
相關(guān)文章:
1. python3.x - python多進程,不能在同一窗口嗎2. django - pycharm 如何配置 python3 的開發(fā)環(huán)境?3. win10 python3.5 matplotlib使用報錯4. python3.x - Python中出現(xiàn)AttributeError: object has no attribute5. 網(wǎng)頁爬蟲 - python3.4.1 request模塊報錯 ’list’ object has no attribute ’get’6. python3.x - python django通過ajax向后端傳json怎么解析7. Python3安裝selenium后下載chormdriver出現(xiàn)問題,大家是什么解決的8. thread - python3開線程9. python3.x - python連oanda的模擬交易api獲取json問題第七問10. python3.x - 如何在云服務(wù)器上運行python腳本?
