understanding operator overloading
Josh Benner
sjbenner at gmail.com
Fri Jun 1 12:39:36 EDT 2012
Is there a good way to trace what's going on under the hood wrt operator
overloading?
I am trying to understand what is happening in the code and output listed
below.
Why doesn't __getitem__ in mylist return the same result as the builtin
list object?
Does it have something to do with the start and stop arguments to slice?
Is the slice object making the call to __len__?
____code___________________________________________________
class mylist():
def __init__(self, data):
self.data = data
def __len__(self):
print('len(self.data) -> self.data = {0}'.format(self.data))
return len(self.data)
def __getitem__(self, index):
print('__getitem__(index) -> index = {0}'.format(index))
return self.data[index]
if __name__ == "__main__":
alist = [1, 2, 4]
blist = mylist(alist)
print('printing alist[-4:]')
print(alist[-4:])
print('printing blist[-4:]')
print(blist[-4:])
print('printing blist[-2]')
print(blist[-2])
____output_________________________________________________
printing alist[-4:]
[1, 2, 4]
printing blist[-4:]
len(self.data) -> self.data = [1, 2, 4]
__getitem__(index) -> index = slice(-1, 9223372036854775807, None)
[4]
printing blist[-2]
__getitem__(index) -> index = -2
2
Best,
Josh Benner
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120601/3be41b68/attachment.html>
More information about the Python-list
mailing list