Python - Dictionary - Modify __getitem__?

前端 未结 2 963
天命终不由人
天命终不由人 2021-01-06 17:45

Ok so i\'ve build my own variable handler which has a __getitem__ function for use when accessing data via data[key], it works great except for when trying to a

相关标签:
2条回答
  • 2021-01-06 18:14

    Remember: tmp = foo['bar']['baz'] is the same as tmp = foo['bar']; tmp = tmp['baz']

    So to allow arbitrary depths your __getitem__ method must return a new object that also contains such a __getitem__ method.

    0 讨论(0)
  • 2021-01-06 18:15

    The fact is that when Python encounters an expression such as data["key"]["subkey"], what is done internally is (data["key"])["subkey"]. That is, the first part of the expression is resolved: the retrievalof the item "key" from the object "data". Then, Python tries do call __getitem__ on the resulting object of that expression. If such resulting object does not have a __getitem__method itself, there is your error.

    There are two possible workarounds there: you should either work with "tuple indexes" - like data["key", "subkey"](and then test on your __getitem__ method wether you got a tuple instance as the key) - or make __getitem__ return an specialized object that also features a __getitem__ method - even if all it does is to log the requested keys.

    0 讨论(0)
提交回复
热议问题