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.