简体   繁体   中英

How do you set up the __contains__ method in python?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM