M
M
Maxim Vasiliev2012-09-16 16:05:16
Python
Maxim Vasiliev, 2012-09-16 16:05:16

__getitem__ cannot be @classmethod

For example, this is the class:

class Class(object):
    @classmethod
    def getitem(*args):
        print 'getitem %s' % (args,)
    @classmethod
    def __getitem__(*args):
        print '__getitem__ %s' % (args,)


The getitem method behaves as expected: it takes as the first parameter Classwhen called both from the class and from the object
. But __getitem__ is called only from the object, and from the class it receives the type as the first parameter:

calling Class.getitem(test)
getitem(<class '__main__.Class'>, 'test')

calling obj.getitem(test)
getitem(<class '__main__.Class'>, 'test')

calling Class[test]
'type' object has no attribute '__getitem__'

calling obj[test]
__getitem__(<class '__main__.Class'>, 'test')


What kind of magic is there inside __getitem__?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Vasiliev, 2012-09-16
@qmax

while writing here on stackoverflow already answered:
All __magic__ methods are looked up in the dictionary of the class, not the object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question