我正在使用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
使用原始的equals属性,代码可以正常运行。 谁能解释我为什么会这样。谢谢。
答案 0 :(得分:1)
因为您要检查多只兔子的相等性! {
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
},
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"port": 5678,
"host": "localhost",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "."
}
]
},
{
"name": "Python: Module",
"type": "python",
"request": "launch",
"module": "enter-your-module-name-here",
"console": "integratedTerminal"
},
{
"name": "Python: Django",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/IA_TD2.py",
"console": "integratedTerminal",
"args": [
"runserver",
"--noreload",
"--nothreading"
],
"django": true
},
{
"name": "Python: Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "app.py"
},
"args": [
"run",
"--no-debugger",
"--no-reload"
],
"jinja": true
},
{
"name": "Python: Current File (External Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "externalTerminal"
},
{
"name": "Python: Current File (None)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "none"
}
]
对象的父母也是兔子,每个对象都有父母的兔子。因此,每次相等检查将递归调用e, f
,直到您到达Rabbit.__eq__
和a