+ 2

How this function is working in python?

https://sololearn.com/compiler-playground/cEUPyQhFa7gb/?ref=app In the last line, if we call print(L[2]). It is calling magic method __getitem__ and print stuffs. But I'm not sure how this magic method is working. Because the parameter the method has is something like getitem(self,index). So shouldn't we call it by : print(L,2) instead of print(L[2]) ? Because now it perfectly matches with magic method parameters..

24th Aug 2025, 7:13 AM
Manav Roy
Manav Roy - avatar
2 Antworten
+ 2
maybe you mean print(L.__getitem__(2)) it's operator overloading. __add__ can be used as +, __getitem__ can be used as [ ]. https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK/operator-overloading-in-python/ but you can also use the __xxx__ version
24th Aug 2025, 7:24 AM
Bob_Li
Bob_Li - avatar
+ 2
Bob_Li Yes right. print(L.__getitem__(2)) does make sense!!
24th Aug 2025, 7:44 AM
Manav Roy
Manav Roy - avatar