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?
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.
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__ .
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With