In this post, we will be talking about how Python likes to deal with “list-like objects”. We will be diving into some quirks of Python that might seem a bit weird and, in the end, we will hopefully teach you how to build something that could actually be useful while avoiding common mistakes.
Let’s start with this snippet.
class FakeList:
def __getitem__(self, index):
if index == 0:
return "zero"
elif index == 1:
return "one"
elif index == 2:
return "two"
elif index == 3:
return "three"
elif index == 4:
return "four"
elif index == 5:
return "five"
elif index == 6:
return "six"
else:
raise IndexError(index)
f = FakeList()
A lot of people will be familiar with this:
f[3]
## <<< 'three'
__getitem__
is the method you override if you want your instances to respond to the square bracket notation. Essentiallyf[3]
is equivalent tof.__getitem__(3)
.
#python #list-like-objects #code #coding #lists #hackernoon-top-story #python-programming-lists #good-company