问题描述
Python(特别是2.6.4)如何一般确定列表成员身份?我已经进行了一些测试以查看其作用:
How does Python (2.6.4, specifically) determine list membership in general? I've run some tests to see what it does:
def main():
obj = fancy_obj(arg='C:\\')
needle = (50, obj)
haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle]
print (1, fancy_obj(arg='C:\\'),) in haystack
print needle in haystack
if __name__ == '__main__':
main()
哪个产量:
False
True
这告诉我Python可能正在检查对象引用,这很有意义.我还能看些更确定的东西吗?
This tells me that Python is probably checking the object references, which makes sense. Is there something more definitive I can look at?
推荐答案
对于列表和元组类型,当且仅当存在一个索引i使得x == y[i]
为true时,x in y
为true.
For the list and tuple types, x in y
is true if and only if there exists an index i such that x == y[i]
is true.
因此,在您的示例中,如果fancy_obj
类将arg
的值存储在实例变量中,并且要实现一个__eq__
方法,如果比较的两个fancy_objs
具有相同的值,则该方法返回True. arg
,则(1, fancy_obj(arg='C:\\'),) in haystack
为True.
So in your example, if the fancy_obj
class stored the value of arg
in an instance variable and were to implement an __eq__
method that returned True if the two fancy_objs
being compared had the same value for arg
then (1, fancy_obj(arg='C:\\'),) in haystack
would be True.
The relevant page of the Standard Library reference is: Built-in Types, specifically 5.6 Sequence Types
这篇关于列表成员的详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!