Skip to content
Snippets Groups Projects
Select Git revision
  • a9c64f67f4c5b0a53ac45358eeea6edc3ef1b91a
  • main default
  • tp2
  • tp1
  • tp3
  • tp3-correction
  • tp2-correction
  • tp1-correction
  • admins
9 results

expression.py

Blame
  • Forked from an inaccessible project.
    expression.py 1001 B
    """
    Expression module defines the structure of an expression.
    """
    from typing import Union
    from calculator.operators import Operator
    
    
    Term: type = int
    Token: type = Union[Operator, Term]
    
    
    class OperatorExpression:
        """
        OperatorExpression class is an expression that contains an operator and two sub-expressions.
        """
    
        def __init__(self, operator: Operator, left, right):
            self.operator = operator
            self.left = left
            self.right = right
    
        def __repr__(self):
            return f"({self.left} {self.operator} {self.right})"
    
        def __call__(self) -> Term:
            return self.operator(self.left(), self.right())
    
    
    class TermExpression:
        """
        TermExpression class is an expression that contains a single term.
        """
    
        def __init__(self, value: Term):
            self.value = value
    
        def __repr__(self):
            return str(self.value)
    
        def __call__(self) -> Term:
            return self.value
    
    
    Expression: type = Union[OperatorExpression, TermExpression]