gpt4 book ai didi

python - 在 Python 中,in 运算符是如何实现的?它是否使用迭代器的 next() 方法?

转载 作者:行者123 更新时间:2023-11-28 22:14:10 25 4
gpt4 key购买 nike

在 Python 中,众所周知,in 检查迭代器(列表、字典等)中的成员资格并在字符串中查找子字符串。我的问题是关于如何实现 in 以实现以下所有功能:1) 测试成员资格,2) 测试子字符串和 3) 访问 for 循环中的下一个元素。例如,当 for i in myList:if i in myList: 被执行时,in 是否调用 myList.__next__() ?如果它确实调用了它,那么它如何处理字符串,因为 str 对象不是迭代器(如在 Python 2.7 中检查的那样),因此没有 next() 方法?如果无法详细讨论 in 的实现,请在此处提供其要点。

最佳答案

类可以通过定义 __contains__ 方法来定义 in 运算符如何作用于该类的实例。

Python data model documentation说:

For objects that don’t define __contains__(), the membership test first tries iteration via __iter__(), then the old sequence iteration protocol via __getitem__(), see this section in the language reference.

Section 6.10.2, "Membership test operations", of the Python language reference有这样的话:

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

For user-defined classes which define the __contains__() method, x in y returns True if y.__contains__(x) returns a true value, and False otherwise.

For user-defined classes which do not define __contains__() but do define __iter__(), x in y is True if some value z with x == z is produced while iterating over y. If an exception is raised during the iteration, it is as if in raised that exception.

Lastly, the old-style iteration protocol is tried: if a class defines __getitem__(), x in y is True if and only if there is a non-negative integer index i such that x == y[i], and all lower integer indices do not raise IndexError exception. (If any other exception is raised, it is as if in raised that exception).

The operator not in is defined to have the inverse true value of in.

如上注释所示,表达式运算符 in 不同于关键字 in,后者构成的一部分 the for statement .在 Python 语法中,in 被“硬编码”为 for 语法的一部分:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
["else" ":" suite]

因此在 for 语句的上下文中,in 不作为运算符,它只是一个分隔 target_list 的句法标记> 来自 expression_list

关于python - 在 Python 中,in 运算符是如何实现的?它是否使用迭代器的 next() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53542860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com