In the interactive interpreter, if you type the following in order you can see some pretty interesting stuff:
1) help()
2) modules
3) __builtin__
When reading through the output for awhile I came across these lines in class bool
:
__or__(...)
x.__or__(y) <==> x|y
and then later on:
__ror__(...)
x.__ror__(y) <==> y|x
This last method appears to describe reverse or. Why does this method exist? What could possibly cause __or__(...)
to return anything different than __ror__(...)
?
Suppose you write your own integer class, and you want it to work with the built-in integers. You might define __or__
class MyInt(int):
def __or__(self, other):
# Not a recommended implementation!
return self | int(other)
so that you can write code like
# Because this is equivalent to MyInt.__or__(MyInt(6), 7)
MyInt(6) | 7
However, Python wouldn't know what to do with
# First interpretation is int.__or__(7, MyInt(6))
7 | MyInt(6)
because int.__or__
wouldn't know how to work with an instance of MyInt
. In such a case, Python swaps the order of the operands and tries
MyInt.__ror__(MyInt(6), 7)
that is, looks for the swapped version of the magic method in the class of the right-hand argument.
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