輕鬆掌握python設計模式之訪問者模式,python設計模式

來源:互聯網
上載者:User

輕鬆掌握python設計模式之訪問者模式,python設計模式

本文執行個體為大家分享了python訪問者模式代碼,供大家參考,具體內容如下

"""訪問者模式"""class Node(object):  passclass A(Node):  passclass B(Node):  passclass C(A, B):  passclass Visitor(object):  def visit(self, node, *args, **kwargs):    meth = None    """python支援多重繼承,在解析父類的__init__時,定義解析順序的是子類的__mro__屬性,內容為一個儲存要解析類順序的元組。"""    """觀察到,super的執行路徑和類的__mro__列舉的類順序吻合;而__mro__的順序可以看作是深搜的結果"""    for cls in node.__class__.__mro__:      """方法名"""      meth_name = 'visit_' + cls.__name__      """getattr()函數是Python自省的核心函數,具體使用大體如下:       擷取對象引用getattr,Getattr用於返回一個對象屬性,或者方法       如果Visitor對象中有屬性meth_name則獲得方法返回的值,否則賦值None      """      meth = getattr(self, meth_name, None)      if meth:        break    if not meth:      meth = self.generic_visit    return meth(node, *args, **kwargs)  def generic_visit(self, node, *args, **kwargs):    print('通常訪問: ' + node.__class__.__name__)  def visit_B(self, node, *args, **kwargs):    print('訪問_B ' + node.__class__.__name__)a = A()b = B()c = C()visitor = Visitor()visitor.visit(a)visitor.visit(b)visitor.visit(c)

運行結果:

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.