Python中的符号计算器:如何正确重写__eq__



我用Python写了一个小的符号计算器来表示实数。

class Symbol:
    def __init__(self, name, negated=False):
        self.name = name
        self.negated = negated
    def __eq__(self, other):
        if not isinstance(other, Symbol):
            print("what do I do?")
        return self.name == other.name and 
               self.negated == other.negated
    def __neg__(self):
        return Symbol(self.name, not self.negated)
    def __pos__(self):
        return Symbol(self.name)
    def __str__(self):
        return "-" + self.name if self.negated else self.name
    def __repr__(self):
        return str(self)

class Add:
    def __init__(self, left, right):
        self.left = left; self.right = right
    def __eq__(self, other):
        if not isinstance(other, Add):
            print("what do I do?")
        return (self.left  == other.left and self.right == other.right) or
               (self.right == other.left and self.left  == other.right)
    def __str__(self):
        return "(%s + %s)" %(self.left, self.right)
    def __repr__(self):
        return str(self)
a = Symbol("a")
b = Symbol("b")
c = Symbol("c")
print(Add(a, b) == Add(b, a)) #commutativity 
print(Add(a, Add(b, c)) == Add(Add(a, b), c)) #associativity

当Python在第二个print语句中检查相等性时,它将比较aAdd(a, b)。这些是不同的类型;我应该如何重写__eq__方法来正确支持关联属性?

Maybe:

def __eq__(self, other)
    th = str(self)
    th = th.replace("(","").replace(")","").replace(" ","")
    ot = str(other).replace("(","")
    ot = ot.replace(")","").replace(" ","")
    return sorted(th.split("+")) == sorted(ot.split("+"))

我不知道这是不是最好的。

编辑:

class A:
  def __init__(self, l, r):
    self.l = l
    self.r = r
  def __str__(self):
    return "(%s + %s)" %(self.l, self.r)
  def __eq__(self, other):
    th = str(self).replace("(","").replace(")","").replace(" ","")
    ot = str(other).replace("(","").replace(")","").replace(" ","")
    return sorted(th.split('+')) == sorted(ot.split('+'))

A('a',A('b','c')) == A('b',A('a','c'))给了我True

最新更新