__call__ method is used to use the object as a method. __iter__ method is used to generate generator objects using the object.
In Python, special methods are a set of predefined methods you can use to enrich your classes. They are easy to recognize because they start and end with double underscores, for example __init__ or __str__ .
Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.
>>> class Thing(object): ... def __index__(self): ... return 1 ... >>> thing = Thing() >>> list_ = ['abc', 'def', 'ghi'] >>> list_[thing] 'def' >>> dict_ = {1: 'potato'} >>> dict_[thing] # KeyError
How does thing
know to represent itself as 1 when accessed by a list, but not by a dict? Don't both magic methods go through __getitem__
? The usage shown for lists could go through __int__
instead so what is the raison d'être for __index__
anyway?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With