why __getitem__ cannot be classmethod?

前端 未结 2 1460
日久生厌
日久生厌 2020-12-10 12:28

Suppose following class:

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


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 12:33

    When you call x[test], the interpreter inspects type(x) for the __getitem__ attribute. In case of Class[test] it's the Class's metaclass, i.e. type. If you want to have a class-wide __getitem__, define it inside a new metaclass. (Needless to say, that's a sort of magic, as anything you do with metaclasses)

    class Meta(type):
        def __getitem__(self, arg):
            print "__getitem__:", arg
    
    
    class X(object):
        __metaclass__ = Meta
    
    X['hello'] # output: __getitem__ hello
    

提交回复
热议问题