Magic Methods
#python
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.
Example:
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
Result:>>>
spam
============
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"
Summary
status | not read | | reprioritisations | |
---|
last reprioritisation on | | | suggested re-reading day | |
---|
started reading on | | | finished reading on | |
---|
Details