Do you want BuboFlash to help you learning these things? Or do you want to add or correct something? Click here to log in or create user.

Magic Methods

The expression x + y is translated into x.__add__(y).

However, if x hasn't implemented __add__, and x and y are of different types, then y.__radd__(x) is called.
There are equivalent r methods for all magic methods just mentioned.
class SpecialString:
def __init__(self, cont):
self.cont = cont

def __truediv__(self, other):
line = "=" * len(other.cont)
return "\n".join([self.cont, line, other.cont])

spam = SpecialString("spam")
hello = SpecialString("Hello world!")
print(spam / hello)Try It Yourself
Hello world!
In the example above, we defined the division operation for our class SpecialString.
If you want to change selection, open original toplevel document below and click on "Move attachment"


statusnot read reprioritisations
last reprioritisation on suggested re-reading day
started reading on finished reading on



Do you want to join discussion? Click here to log in or create user.