What happens when you call `if key in dict`

前端 未结 3 897
旧时难觅i
旧时难觅i 2020-12-11 06:05

I have a class (let\'s call it myClass) that implements both __hash__ and __eq__. I also have a dict that maps myCl

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 06:34

    First, __hash__(myNewMyClassObj) gets called. If no object with the same hash is found in the dictionary, Python assumes myNewMyClassObj is not in the dictionary. (Note that Python requires that whenever __eq__ evaluates as equal for two objects, their __hash__ must be identical.)

    If some objects with the same __hash__ are found in the dictionary, __eq__ gets called on each of them. If __eq__ evaluates as equal for any of them, the myNewMyClassObj in dict_ returns True.

    Thus, you just need to make sure both __eq__ and __hash__ are fast.

    To your follow up question: yes, dict_ stores only one of a set of equivalent MyClass objects (as defined by __eq__). (As does set.)

    Note that __eq__ is only called on the objects that had the same hash and got allocated to the same bucket. The number of such objects is usually a very small number (dict implementation makes sure of that). So you still have (roughly) O(1) lookup performance.

提交回复
热议问题