python - 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") my intention have
book[book.note] returns "note" it seems __getitem__() not overrideable, unlike test(). how make work ?
you're using metaclass here. isn't strictly inheritance: you've defined the class of class book custom, whereas used type. because magic methods __getitem__ looked directly on class, , not on instance, indexing book[whatever] call __getitem__ method of class of book, happens custom.
my intention have
book[book.note]returns "note"
in case, should make class of book implement __getitem__ such returns "note". since class of book custom, change needs made:
class custom(type): def __getitem__(cls, item): return cls.name[item] ... class book(metaclass=custom): ... # is, although don't need @classmethod __getitem__ book[book.note] # "note" book[1] # "pad"
Comments
Post a Comment