Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __index__ special method

Tags:

People also ask

What is __ method __ in Python?

__call__ method is used to use the object as a method. __iter__ method is used to generate generator objects using the object.

What are special methods in Python?

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__ .

Is __ init __ a magic method?

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?