Easy understanding of the visitor mode of the python design mode and the python Design Mode

Source: Internet
Author: User

Easy understanding of the visitor mode of the python design mode and the python Design Mode

This article provides examples of the python visitor mode code for your reference. The specific content is as follows:

"Visitor mode" 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 supports multiple inheritance. when parsing the _ init _ of the parent class, the _ mro _ attribute of the subclass defines the resolution sequence. The content is a tuple that stores the class sequence to be parsed. "Observed that the super execution path matches the class sequence listed by _ mro _ of the class; the order of _ mro _ can be viewed as the result of a deep search "" for cls in node. _ class __. _ mro __: "method name" "meth_name = 'visit _ '+ cls. the _ name _ "getattr () function is the core function of Python introspection. The usage is generally as follows: Get the object reference getattr, and Getattr is used to return an object attribute, alternatively, if the Visitor object contains the meth_name attribute, the value returned by the method is obtained. Otherwise, the value is set to 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 ('common access: '+ 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) visitor. visit (B) visitor. visit (c)

Running result:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.