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.