Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the names of the magic methods for the operators "is" and "in"?

I would like to make bool binary operations using the magic methods for these operators. For example, I can get a < b as getattr(a, '__lt__')(b) or a == b as getattr(a, '__eq__')(b).

Can I get a in b and a is b in such a way?

like image 738
nik Avatar asked Dec 05 '16 18:12

nik


People also ask

What are magic methods?

Magic methods are special methods in python that have double underscores (dunder) on both sides of the method name. Magic methods are predominantly used for operator overloading.

How many magic methods are there in Python?

Let's take a closer look at these 3 magic methods: __new__(cls, [...) __new__ is the first method to get called in an object's instantiation. It takes the class, then any other arguments that it will pass along to __init__ .

Which is magic method for greater than operator?

To use the greater than operator on custom objects, define the __gt__() “dunder” magic method that takes two arguments: self and other . You can then use attributes of the custom objects to determine if one is greater than the other.


2 Answers

For in, the correct dunder method is __contains__.

There is no method for is, because this is equivalent to id(a) == id(b). It compares the actual object ID used under the hood by Python, so is used to compare object identity, not object contents. Overwriting it within a class would break Python's object model, so it is not allowed.

like image 119
SethMMorton Avatar answered Sep 17 '22 11:09

SethMMorton


in is __contains__ and is does not have a dunder method. I strongly suggest you use the functions in the operator module:

a < b  => operator.lt(a, b)
a == b => operator.eq(a, b)
a in b => operator.contains(a, b)
a is b => operator.is_(a, b)
like image 20
Dan D. Avatar answered Sep 16 '22 11:09

Dan D.