Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange thing when Python __setitem__ use multiple key

I wan't to test the type of key when use __setitem__. But strangely I found some part of code be omitted when use mutiple keys. Here is my test class:

class foo():
    def __init__(self):
        self.data=[[1,2],[3,4],[5,6]]

    def __getitem__(self, key):
        return self.data[key]

    def __setitem__(self, key, value):
        print('Key is {0}, type of key is {1}'.format(key,type(key)))
        self.data[key] = value

f = foo()

When use one key it's ok:

>>>f[1] = [0,0]
   Key is 1, type of key is <class 'int'>
>>>f[1]
   [0, 0]

when use two keys, result is correct, but why nothing be printed out

>>>f[1][1] = 100

>>>f[1][1]
   100

I'm new in python any suggestion will appreciated!

like image 806
Macer Avatar asked Mar 22 '16 09:03

Macer


2 Answers

f[1][1] = 0 is equivalent to

f.__getitem__(1).__setitem__(1, 0)

It calls __getitem__ on your custom class; and this returns [0, 0] or [3, 4] or whatever was stored in f[1]; in any case this value is a plain Python list; then calls the __setitem__ on this list. list.__setitem__ does not print anything.


f[1] calls your __getitem__ and thus returns a list ([3,4] in the case of the freshly initialized object). Then, the second indexing operation f[1][1] indexes the object that was returned, the list [3,4], which is not an instance of your class, but simply a list type (as returned by your class).

like image 22
egpbos Avatar answered Sep 17 '22 22:09

egpbos