7
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")

My intention is to have

Book[Book.Note] returns "Note"

It seems __getitem__() is not overrideable, unlike test(). How do I make it work ?

1 Answer 1

7

You're using a metaclass here. This isn't strictly inheritance: you've defined the class of the class Book as Custom, whereas it used to be type. Because magic methods like __getitem__ are looked up directly on the class, and not on the instance, indexing Book[whatever] will actually call the __getitem__ method of the class of Book, which happens to be Custom.

My intention is to have

Book[Book.Note] 

returns "Note"

In that case, you should make the class of Book implement __getitem__ such that it returns "Note". Since the class of Book is Custom, this is where the change needs to be made:

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"
Sign up to request clarification or add additional context in comments.

3 Comments

@user1502776 That's odd. I'm using Python 3 myself and it works. Let me see if I can put together a demo.
Your explanation demonstrates profound understanding of Python workings. Could you please recommend a book to read on ..?
@user1502776 I wouldn't say I have a rock solid understanding of Python, even after a long time using it, but if I had to suggest anything I'd suggest reading the docs; they're pretty good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.