by Albert Major
1 + 2 → numeric addition'a' + 'b' → string concatenation[1] + [2] → list concatenation+, ==, etc., should mean for your own class using special methods (called dunder methods).ComplexA simple example is a class for complex numbers. A complex number has:
r)c)class Complex:
def __init__(self, r, c):
self.r = r
self.c = c
This creates an object like Complex(3, 2) representing 3 + 2i.
__str__ and __repr____str__ defines what happens when you call str(obj) or use print(obj).__repr__ defines what happens in the Python shell (interactive display).def __str__(self):
return str(self.r) + "+" + str(self.c) + "i"
Key rules: