【发布时间】:2012-09-08 22:44:51
【问题描述】:
假设以下类:
class Class(object):
@classmethod
def getitem(*args):
print 'getitem %s' % (args,)
@classmethod
def __getitem__(*args):
print '__getitem__ %s' % (args,)
getitem 方法的行为符合预期:它接收Class 作为第一个参数,但__getitem__ 接收type 作为第一个参数:
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')
__getitem__ 背后有什么魔力?
【问题讨论】:
标签: python class-method