\您可以通过创建实现标准 python 数据模型 ( http://docs.python.org/2/reference/datamodel.html ) 的 Symbol 和 Operator 类来做到这一点。这将使事情保持与 python 运算符优先级相同的顺序,尽管您可以通过括号重新排列:
class Symbol(object):
def __init__(self, name):
self._name = name
def __str__(self):
return str(self._name)
def __div__(self, other):
return Div(self, other)
def __mul__(self, other):
return Mult(self, other)
def __add__(self, other):
return Add(self, other)
def __sub__(self, other):
return Sub(self, other)
def __rdiv__(self, other):
return Div(other, self)
def __rmul__(self, other):
return Mult(other, self)
def __radd__(self, other):
return Add(other, self)
def __rsub__(self, other):
return Sub(other, self)
class Operation(Symbol):
def __init__(self, a, b, op):
self._a = a
self._b = b
self._op = op
def __str__(self):
return self._op.format(self._a, self._b)
class Add(Operation):
precedence = 0
def __init__(self, a, b):
super(Add, self).__init__(a, b, "{0} + {1}")
class Sub(Operation):
precedence = 0
def __init__(self, a, b):
super(Sub, self).__init__(a, b, "{0} - {1}")
class Mult(Operation):
precedence = 1
def __init__(self, a, b):
if isinstance(a, Operation) and a.precedence < Mult.precedence:
a_form = "({0})"
else:
a_form = "{0}"
if isinstance(b, Operation) and b.precedence < Mult.precedence:
b_form = "({1})"
else:
b_form = "{1}"
super(Mult, self).__init__(a, b, a_form + " " + b_form)
class Div(Operation):
precedence = 1
def __init__(self, a, b):
super(Div, self).__init__(a, b, "\\frac{{{0}}}{{{1}}}")
A = Symbol('A')
B = Symbol('B')
C = Symbol('C')
x = Symbol('x')
然后:
>>> print (C - A * x) / (B)
\frac{C - A x}{B}
>>> print (C * (A + B))
C (A + B)
>>> print (C * (A + B + A + B + C + x))
C (A + B + A + B + C + x)