Package pypat :: Package behavioral :: Module visitor
[hide private]
[frames] | no frames]

Source Code for Module pypat.behavioral.visitor

 1  from abc import ABCMeta, abstractmethod 
2 3 4 -class Visitor(metaclass=ABCMeta):
5 """ 6 Abstract Visitor class as part of the Visitor Design Pattern. 7 8 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage} 9 - External Visitor Design Pattern documentation: U{https://en.wikipedia.org/wiki/Visitor_pattern} 10 """
11 - def visit(self, node, *args, **kwargs):
12 """ 13 Visit the visitor with some object. 14 15 @param node: An object to call a visitor method with. 16 @param args: Arguments to go with the visitor method call. 17 @param kwargs: Keyword arguments to go with the visitor method call. 18 @return: The return value of the method that was called for visiting object. 19 """ 20 method = None 21 for cls in node.__class__.__mro__: 22 method_name = 'visit_'+cls.__name__.lower() 23 method = getattr(self, method_name, None) 24 if method: 25 break 26 27 if not method: 28 method = self.generic_visit 29 return method(node, *args, **kwargs)
30 31 @abstractmethod
32 - def generic_visit(self, node, *args, **kwargs):
33 """ 34 The method to call if no methods were found for a visiting object. 35 36 @param node: An object to call a visitor method with. 37 @param args: Arguments to go with the visitor method call. 38 @param kwargs: Keyword arguments to go with the visitor method call. 39 """
40
41 42 -class Visitee(object):
43 """ 44 A base class for objects that wish to be able to be visited by a Visitor class. 45 46 - External Usage documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Behavioral-Pattern-Usage} 47 - External Visitor Design Pattern documentation: U{https://en.wikipedia.org/wiki/Visitor_pattern} 48 """
49 - def accept(self, visitor, *args, **kwargs):
50 """ 51 Have a visitor visit this class instance. 52 53 @param visitor: The visitor to visit. 54 @type visitor: Visitor 55 @param args: Any args to send with the visit. 56 @param kwargs: Any kwargs to send with the visit. 57 """ 58 return visitor.visit(self, *args, **kwargs)
59