Python for Java Programmers
Chapter 8: Object-oriented programming
Magic/Dunder methods
We have seen the special constructor method __init__() earlier.
Python offers more magic methods that can be used to make your custom classes act like Python built-in types.
Here are some examples:
__str__()is used when printing or converting an object into a string. In fact,str(x)invokesx.__str__(). For example, you might wantprint(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 class instance to be used in for loops
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |