Python __index__ special method

前端 未结 3 1976
南旧
南旧 2021-01-01 19:47
>>> class Thing(object):
...     def __index__(self):
...         return 1
... 
>>> thing = Thing()
>>> list_ = [\'abc\', \'def\', \'ghi\'         


        
3条回答
  •  渐次进展
    2021-01-01 20:28

    Dict and List does not implement __getitem__ the same way. Dict objects uses a comparison (__eq__) on __hash__ of objects as key to use in __getitem__.

    To make Thing usable for dict you have to implement both hash and eq.

提交回复
热议问题