我在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
语句中检查相等性时,它会将a
与Add(a, b)
进行比较。这些是不同的类型;我应该如何覆盖__eq__
方法以正确支持associative property?
答案 0 :(得分:2)
也许:
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