SoFunction
Updated on 2024-10-28

Python design patterns of the principles and usage of the interpreter pattern example analysis

This article example describes the principles and usage of Python design patterns of the interpreter pattern. Shared for your reference, as follows:

Interpreter Pattern: Given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language.

Here is a demo of the interpreter pattern:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
big talk about design patterns
design pattern——interpreter mode
interpreter mode(Interpreter Pattern):Given a language,A representation of the grammar that defines it,and define an interpreter,This interpreter uses this representation to interpret sentences in the language.
"""
# Abstract an interpreter class
class AbstractExpression(object):
  def interpreter(self, context):
    pass
# Concrete Interpreter - Terminal Inherit Abstract Interpreter
class TerminalExpression(AbstractExpression):
  def interpreter(self, context):
    print "Terminal Interpreter",context
# Concrete Interpreter - Terminal Inherit Abstract Interpreter
class NotTerminalExpression(AbstractExpression):
  def interpreter(self, context):
    print "Non-terminal interpreter",context
class Context(object):
  def __init__(self):
     = ""
if __name__ == "__main__":
  context = Context()
   = 'Andy'
  arr_list = [NotTerminalExpression(),TerminalExpression(),TerminalExpression()]
  for entry in arr_list:
    (context)

Run results:

The design of the above class is shown below:

The interpreter pattern can be used when there is a language to be executed and the sentences of that language can be represented as an abstract syntax tree

More about Python related content can be viewed on this site's topic: thePython Data Structures and Algorithms Tutorial》、《Python Socket Programming Tips Summary》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.