python委托模式详细解释
收集了網上的三個例子,然后做了些注釋:
#!/usr/bin/env python3 # -*- coding: utf-8 -*-class Wrapper:def __init__(self, obj):self.wrapper = objprint self.wrapperprint type(self.wrapper)print"-"*100def __getattr__(self, item):print("trace:", item)return getattr(self.wrapper, item)if __name__ == '__main__':x = Wrapper([1, 2, 3, 4])x.append(35)x.remove(2)print(x.wrapper) # [1,3,4,35]在__getattr__(self,item)中,將攔截到的屬性,讓被委托對象去使用。
python 中的屬性概念,和Java中的屬性概念是不同的。Java中的屬性,就是指類中定義的成員變量,絕對不包含方法。而在python中,任何能以obj.xx形式調用的東西,全部可以稱為屬性。無論是方法,還是變量,還是對象。
所以上述代碼中調用x.append(N),實際上是讓x的屬性wrapper去調用append(N)方法。
上面傳入的參數是[1,2,3,4],是一個list類型的對象,該對象自然可以調用append remove這些方法。
這個轉載自:http://blog.csdn.net/DucklikeJAVA/article/details/73729212
---------------------------------------------------------------------------------------------------------------
#-*- encoding:utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') class A:def f_one(self, x):print"here is f_one"print"x=",xprint"-"*100def f_two(self):print"here is f_two"print"-"*100class B(A):def __init__(self):self._a = A()#也就是說在類B中有個成員變量例化了類A,_a是A的對象,不要太在意_a這個奇怪的名字def f_one(self, x):return self._a.f_one(x)def f_two(self):return self._a.f_two()def f_three(self):print"Here is B(A)" if __name__ == '__main__':b_test=B()x=6b_test.f_one(x)b_test.f_two()這就是一個最簡單的委托,將A的實例在B類中生成,并且轉化為B的一個私有屬性,當我們需要訪問A的屬性的時候,加入我們只暴露B出來,這時候就只能通過B類來訪問A類,這就達到了委托的效果。
上面的這種方法使用情景為:有幾個方法需要委托,當我們需要大量委托的時候這顯然不是一個好辦法,這時候還有另一個更巧妙的方法:getattr()方法,下面請看代碼:
#-*- encoding:utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') class A:def f_one(self, x):print"here is f_one"print"x=",xprint"-"*100def f_two(self):print"here is f_two"print"-"*100class B(A):def __init__(self):self._a = A()def f_three(self):passdef __getattr__(self, name):#相當于重寫了__getattr__,利用__getattr_來實現委托的效果(其實委托就是甩鍋的意思啦,B搞不定,甩鍋給A)return getattr(self._a, name) if __name__ == '__main__':b_test=B()x=6b_test.f_one(x)b_test.f_two()這里要注意一下這個新的方法,這個方法的作用是用來查找所有的屬性,放在這里時,如果代碼中嘗試訪問這個類中不存在的屬性時,會去調用實例_a中的屬性,這樣就可以實現大量的代理。
總結
以上是生活随笔為你收集整理的python委托模式详细解释的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python可变数据类型与不可变数据类型
- 下一篇: websocket python爬虫_p