Python List Class __contains__ Method Functionality

点点圈 提交于 2019-12-12 08:28:19

问题


Does the __contains__ method of a list class check whether an object itself is an element of a list, or does it check whether the list contains an element equivalent to the given parameter?

Could you give me an example to demonstrate?


回答1:


>>> a = [[]]
>>> b = []
>>> b in a
True
>>> b is a[0]
False

This proves that it is a value check (by default at least), not an identity check. Keep in mind though that a class can if desired override __contains__() to make it an identity check. But again, by default, no.




回答2:


It depends on the class how it does the check. For the builtin list it uses the == operator; otherwise you couldn't e.g. use 'something' in somelist safely.

To be more specific, it check if the item is equal to an item in the list - so internally it's most likely a hash(a) == hash(b) comparison; if the hashes are equal the objects itself are probably compared, too.



来源:https://stackoverflow.com/questions/10210233/python-list-class-contains-method-functionality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!