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

How to override __getitem__ when it's a class method?

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"

似乎 __getitem__() 不可覆盖,不像 test()。我如何让它发挥作用?

您在此处使用元class。这不是严格意义上的继承:您已经将 class Bookclass 定义为 Custom,而它过去是是 type。因为像 __getitem__ 这样的魔术方法是直接在 class 上查找的,而不是在实例上查找的,索引 Book[whatever] 实际上会调用 class 的 __getitem__ 方法Book,恰好是 Custom

My intention is to have

Book[Book.Note] 

returns "Note"

在这种情况下,您应该使 Book 的 class 实现 __getitem__,使其 returns "Note"。由于Book的class是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"