Easy to master python design pattern visitor patterns _python

Source: Internet
Author: User

This example of this article for you to share the Python visitor pattern code for your reference, the details are as follows

"" Visitor Mode "" Class Node (object): Pass class A (node): Pass class B (node): Pass Class C (A, B): Pass class Visito R (Object): Def visit (Self, node, *args, **kwargs): Meth = None "" "Python supports multiple inheritance, when parsing the __init__ of a parent class, it is a subclass of the __mro_ that defines the parsing order. _ property, which is a tuple that stores the order in which you want to resolve classes. "" "" "" observed that the execution path of super is in accordance with the class order of the class's __mro__ enumeration, and that the __mro__ order can be considered as the result of a deep search "" for the CLS in node.__class__.__mro__: "" "Method Name" " The "meth_name = ' visit_ ' + cls.__name__" "getattr () function is the core function of Python introspection, which is generally used as follows: Get object reference getattr,getattr used to return
      Returns an object property, or if a property meth_name in the visitor object gets the value returned by the method, the assignment is None "" "Meth = GetAttr (self, meth_name, None) If Meth:break if not Meth:meth = self.generic_visit return Meth (node, *args, **kwargs) def G  Eneric_visit (Self, node, *args, **kwargs): print (' usually accessed: ' + node.__class__.__name__ ') def visit_b (Self, node, *args, **kwargs): Print (' Access _b ' + node.__class__.__name__) A = a () b = b () c = c () visitor = Visitor () visitor.visit (a) Vis ItoR.visit (b) visitor.visit (c)
 

Run the results as shown in figure:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.