首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python中的符号计算器:如何正确覆盖__eq__

Python中的符号计算器:如何正确覆盖__eq__
EN

Stack Overflow用户
提问于 2015-09-24 19:29:25
回答 1查看 111关注 0票数 0

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

代码语言:javascript
复制
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__方法才能正确地支持结合性质

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-24 19:37:13

也许:

代码语言:javascript
复制
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("+"))

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

编辑:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32769439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档