Skip to content Skip to sidebar Skip to footer

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 underst

Solution 1:

The __contains__ method on an object doesn't callin; 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.

Solution 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.

Post a Comment for "How Do You Set Up The __contains__ Method In Python?"