你如何在python中设置__contains__方法?

You*_*Sci 3 python methods class contains

我无法理解如何在我的班级中正确设置包含方法.我知道当你调用它时它会自动使用"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
Run Code Online (Sandbox Code Playgroud)

但是,下一个应该执行相同操作的方法使用contains方法,以便我们可以在main函数中使用in来调用它.我只有这个:

def __contains__(self, anotherCircle):
    if anotherCircle in self:
        return True 
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我遇到了多个错误.我想我错过了自己的一些东西,但我不确定是什么?有人可以试着向我解释当你编写像这样的包含方法时你究竟需要做什么?

Ian*_*and 9

__contains__对象上的方法不调用 in ; 相反,它是in运营商所称的.

当你写作

if circle1 in circle2:
Run Code Online (Sandbox Code Playgroud)

python解释器将看到这circle2是一个Circle对象,并将查找为其__contains__定义的方法.它基本上会尝试打电话

circle2.__contains__(circle1)
Run Code Online (Sandbox Code Playgroud)

这意味着您需要在__contains__不使用的情况下编写方法in,否则您将编写永不结束的递归方法.