How do you set up the __contains__ method in python?

旧时模样 提交于 2019-12-23 19:42:14

问题


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.

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

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?


回答1:


The __contains__ method on an object doesn't call in; rather, it is what the in operator calls.

When you write

if circle1 in circle2:

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)

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.




回答2:


Your __contains__ method must use the same logic as your original contains method. Otherwise how will Python know what it means for one circle to contain another? You have to tell it, that's what the __contains__ method is for. You can either get __contains__ to call contains, or just put the whole code in that method instead.



来源:https://stackoverflow.com/questions/14766767/how-do-you-set-up-the-contains-method-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!