如何在python中设置__contains__方法? [英] How do you set up the __contains__ method in python?
问题描述
我无法理解如何在我的课程中正确设置包含方法。我知道它会自动使用操作符in当你调用它,我只是不认为我理解如何正确设置它。
I'm having trouble understanding how to properly set up a contains method in my class. I know it automatically uses the operator "in" when you call it, i just don't think I understand how to set it up correctly.
我必须使用它以查看anotherCircle是否包含在特定圆(两个来自用户的输入)中。教授为我们做了两种不同类型的方法。
I have to use it to see if anotherCircle is contained within a specific circle (both input from the user). The prof had us do two different types of methods for this.
第一个我没有问题,或多或少了解它在做什么,它如下:
The first one I have no problems with and more or less understand what it is doing, It is as follows:
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
但是,接下来的方法应该做同样的事情, strong>包含方法,以便我们可以在主函数中使用 in 来调用它。我所有的是这样:
However, the next method, which is supposed to do the same thing, uses the contains method so that we can call it with in in the main function. All I have is this:
def __contains__(self, anotherCircle):
if anotherCircle in self:
return True
当我试图运行这个时,我得到了多个错误。我想我错过了自我,但我不知道什么?有人可以尝试向我解释,当你编写包含方法时,你需要做什么?
I get multiple errors when I try to run this. I think i'm missing something on self, but I'm not sure what? Could someone please try to explain to me what exactly you need to do when you're writing a contains method such as this?
推荐答案
__包含对象上的__
方法不会 c>;
The __contains__
method on an object doesn't call in
; rather, it is what the in
operator calls.
当你写
if circle1 in circle2:
python解释器将会看到 circle2
是一个Circle对象,并且将查找为其定义的 __包含__
方法。它实质上会尝试调用
The python interpreter will see that circle2
is a Circle object, and will look for a __contains__
method defined for it. It will essentially try to call
circle2.__contains__(circle1)
这意味着您需要写 __包含__
方法,而不使用 c $ c>,否则你将编写一个从不结束的递归方法。
This means that you need to write your __contains__
method without using in
, or else you will be writing a recursive method that never ends.
这篇关于如何在python中设置__contains__方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!