/ Design Patterns / Behavioral patterns / Interpreter Interpreter Design Pattern in Python Back to Interpreter description """ Define a represention for a grammar of the given language along with an interpreter that uses the representation to interpret sentences in the language. """ import abc class AbstractExpression(metaclass=abc.ABCMeta): """ Declare an abstract Interpret operation that is common to all nodes in the abstract syntax tree. """ @abc.abstractmethod def interpret(self): pass class NonterminalExpression(AbstractExpression): """ Implement an Interpret operation for nonterminal symbols in the grammar. """ def __init__(self, expression): self._expression = expression def interpret(self): self._expression.interpret() class TerminalExpression(AbstractExpression): """ Implement an Interpret operation associated with terminal symbols in the grammar. """ def interpret(self): pass def main(): abstract_syntax_tree = NonterminalExpression(TerminalExpression()) abstract_syntax_tree.interpret() if __name__ == "__main__": main() Support our free website and own the eBook! 22 design patterns and 8 principles explained in depth 406 well-structured, easy to read, jargon-free pages 228 clear and helpful illustrations and diagrams An archive with code examples in 4 languages All devices supported: EPUB/MOBI/PDF formats Learn more...