Special methods
We have seen the special constructor method __init__() earlier.
Python offers more special methods that can be used to make classes act like Python built-in types.
Here are some examples:
__str__()is used when printing. In fact,str()invokesx.__str__(). Useful if you want for exampleprint(Person)to return something prettier and more informative than<__main__.Person object at 0x7ffe1cf127c0>.__add__(),__sub__(),__mul__(),__truediv__(),__pow__()will overload their respective mathematical operators.- for example,
x+yactually invokesx.__add__(y).
- for example,
- For overloading boolean operators:
__lt__(),__le__(),__gt__(),__ge__(),__eq__(),__ne__()(<,<=,>,>=,==,!=) - Collections:
__len__()(len(x)invokesx.__len__())__contains__()(item in xinvokesx.__contains__(item))__getitem__()(x[key]invokesx.__getitem__(key))__setitem__()(x[key] = iteminvokesx.__setitem__(key, item))__iter__()is used to allow the type to be used in for loops
Example
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, other):
return Vector(self.a + other.a, self.b + other.b)
def __str__(self):
return f"Vector ({self.a}, {self.b})"
v1 = Vector(1, 2)
v2 = Vector(5, 7)
v3 = v1 + v2
print (v3)