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

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -