【问题标题】:Why is equality attribute of a class calling itself over and over?为什么一个类的相等属性一遍又一遍地调用自己?
【发布时间】:2019-07-06 06:08:25
【问题描述】:

我正在使用 MIT OCW 并且刚刚了解了课程。因此,当在一对实例上调用相等方法时,我的代码(从原始代码编辑)一遍又一遍地调用自己。代码如下:

class Animal(object):
def __init__(self, age):
    self.age = age
    self.name = None
def __str__(self):
    return "animal:"+str(self.name)+":"+str(self.age)


class Rabbit(Animal):
    tag = 1
    def __init__(self, age, parent1=None, parent2=None):
        Animal.__init__(self, age)
        self.parent1 = parent1
        self.parent2 = parent2
        self.rid = Rabbit.tag
        Rabbit.tag += 1
    def __eq__(self, other):
        print('entering equality')
        print(self.parent1)
        print(self.parent2)
        parents_same = self.parent1== other.parent1 and self.parent2== other.parent2
        print('1st comp')
        parents_opposite = self.parent2 == other.parent1 and self.parent1== other.parent2
        print('2nd comp')
        return parents_same or parents_opposite

a=Rabbit(6)
b=Rabbit(7)
c=Rabbit(5,a,b)
d=Rabbit(3,a,b)
e=Rabbit(2,c,d)
f=Rabbit(1,c,d)

print(e==f)

运行此代码时,可以看到 Python 多次进入相等循环。 下面是原始的 eq 属性:

def __eq__(self, other):
    parents_same = self.parent1.rid == other.parent1.rid \
    and self.parent2.rid == other.parent2.rid
    parents_opposite = self.parent2.rid == other.parent1.rid \
    and self.parent1.rid == other.parent2.rid
    return parents_same or parents_opposite

代码在原始的相等属性下运行得很好。 谁能解释我为什么会这样。谢谢。

【问题讨论】:

  • parent1parent2 属性的值是Rabbit也是 实例,因此== 使用Rabbit.__eq__。最终,这样的调用将None 作为两个参数并返回一个值,而无需再次调用Rabbit.__eq__
  • 每个eq 调用需要对其他兔子对象进行最多3 次== 比较(假设兔子不能有重复的父对象)。每一个都需要对其他兔子对象进行多达 3 次== 比较。以此类推。
  • 我认为您真正要问的是,“有没有什么方法可以检查父对象的引用身份而不调用它们的__eq__ 行为,并且没有需要检查他们的摆脱吗?”。假设每只 Rabbit 的摆脱都是全球唯一的,那么您基本上已经重新发明了 id() - 您可以改为使用 self.parent1 is self.parent2
  • 也就是说,如果两只兔子有相同的父母,为什么它们被认为是平等的?
  • 这就是那个特定示例中定义平等的方式。也许是平等的出身。非常感谢你们。

标签: python class oop methods attributes


【解决方案1】:

因为您正在检查多个兔子是否相等! e, f对象的父母也是兔子,每个人都有兔子给父母。所以,每个相等检查都会递归调用Rabbit.__eq__,直到你到达ab

【讨论】:

  • 谢谢。由于我还是新手,所以无法投票赞成您的答案。
猜你喜欢
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 2014-09-04
  • 1970-01-01
相关资源
最近更新 更多