我无法理解如何在我的类中正确设置包含 方法。我知道当你调用它时它会自动使用运算符“in”,我只是不明白如何正确设置它。
我必须使用它来查看 anotherCircle 是否包含在特定圆圈中(均来自用户输入)。教授让我们为此做了两种不同类型的方法。
第一个我没有问题,或多或少明白它在做什么,如下:
def contains(self, circle2d):
dist = math.sqrt((circle2d._x - self._x)**2 + (circle2d._y - self._y)**2) #Distance of second circle's coords from the first circle's coords
if dist + circle2d._radius <= self._radius:
return True
然而,下一个方法,应该做同样的事情,使用contains方法,这样我们就可以在主函数中用in调用它。我只有这个:
def __contains__(self, anotherCircle):
if anotherCircle in self:
return True
当我尝试运行它时出现多个错误。我想我自己遗漏了一些东西,但我不确定是什么?有人可以尝试向我解释当您编写这样的 contains 方法时您到底需要做什么吗?
最佳答案
对象上的 __contains__
方法不会调用 in
;相反,它是 in
运算符调用的内容。
当你写作时
if circle1 in circle2:
python 解释器将看到 circle2
是一个 Circle 对象,并将寻找为其定义的 __contains__
方法。它基本上会尝试调用
circle2.__contains__(circle1)
这意味着您需要在不使用in
的情况下编写__contains__
方法,否则您将编写一个永不结束的递归方法。
关于python - 你如何在 python 中设置 __contains__ 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14766767/