当它是类方法时如何覆盖__getitem__?

时间:2015-05-31 03:51:31

标签: python abstract-class

class Custom(type):
    @classmethod
    def __getitem__(cls, item):
        raise NotImplementedError("")

    @classmethod
    def test(cls):
        print("class custom : test")

class Book(metaclass=Custom):
    Note = 0
    Pad = 1

    Name = { Note : "Note", Pad : "Pad"}

    @classmethod
    def __getitem__(cls, item):
        return Book.Name[item]

    @classmethod
    def test(cls):
        print("class book: test")

我的意图是

Book[Book.Note] returns "Note"

与test()不同,似乎__getitem __()不可重写。我如何使它工作?

1 个答案:

答案 0 :(得分:5)

你在这里使用的是元类。这不是严格的继承:您已将类Book定义为Custom,而它曾经是type。因为__getitem__等魔术方法直接在类上查找,而不是在实例上查找,索引Book[whatever]实际上会调用__getitem__类的Book方法,碰巧是Custom

  

我的意图是

Book[Book.Note] 
     

返回“注意”

在这种情况下,您应该使Book类实现__getitem__,使其返回"Note"。由于Book的等级为Custom,因此需要进行更改:

class Custom(type):
    def __getitem__(cls, item):
        return cls.Name[item]
    ...

class Book(metaclass=Custom):
    ... # as is, although you don't need the @classmethod __getitem__

Book[Book.Note] # "Note"
Book[1]         # "Pad"