假设以下课程:
class Class(object):
@classmethod
def getitem(*args):
print 'getitem %s' % (args,)
@classmethod
def __getitem__(*args):
print '__getitem__ %s' % (args,)
Run Code Online (Sandbox Code Playgroud)
getitem方法的行为符合预期:它Class作为第一个arg __getitem__接收,但type作为第一个arg 接收:
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')
Run Code Online (Sandbox Code Playgroud)
背后有什么魔力__getitem__?