gpt4 book ai didi

python - `in` 为生成器定义

转载 作者:行者123 更新时间:2023-12-03 21:44:55 25 4
gpt4 key购买 nike

为什么是 in为生成器定义的运算符?

>>> def foo():
... yield 42
...
>>>
>>> f = foo()
>>> 10 in f
False
有哪些可能的用例?
我知道 range(...)对象有 __contains__定义函数,以便我们可以执行以下操作:
>>> r = range(10)
>>> 4 in r
True
>>> r.__contains__
<method-wrapper '__contains__' of range object at 0x7f82bd51cc00>
但是 f上面没有 __contains__方法。

最佳答案

“可能的用例是什么?”检查生成器是否会产生一些值。
Dunder 方法充当与其关联的特定语法的 Hook 。 __contains__不是某种与x in y 的一对一映射吗? .该语言最终定义了这些运算符的语义。
来自 documentation of membership testing ,我们看到x in y有几种方法被评估,取决于所涉及的对象的各种属性。我已经为生成器对象添加了相关的对象,它没有定义 __contains__但是是可迭代的,即它们定义了 __iter__方法:

The operators in and not in test for membership. x in s evaluates toTrue if x is a member of s, and False otherwise. x not in s returnsthe negation of x in s. All built-in sequences and set types supportthis as well as dictionary, for which in tests whether the dictionaryhas a given key. For container types such as list, tuple, set,frozenset, dict, or collections.deque, the expression x in y isequivalent 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 asubstring of y. An equivalent test is y.find(x) != -1. Empty stringsare 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 iny returns True if y.__contains__(x) returns a true value, and Falseotherwise.

For user-defined classes which do not define contains() but dodefine __iter__(), x in y is True if some value z, for which theexpression x is z or x == z is true, is produced while iterating overy. If an exception is raised during the iteration, it is as if inraised 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 is y[i] or x == y[i], and no lower integerindex raises the IndexError exception. (If any other exception israised, it is as if in raised that exception).

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


总而言之, x in y将为以下对象定义:
  • 是字符串还是字节,定义为子串关系。
  • 定义 __contains__ 的类型
  • 作为迭代器的类型,即定义 __iter__
  • 旧式迭代协议(protocol)(依赖 __getitem__ )

  • 发电机分为 3 种。
    更广泛地说,你真的不应该直接使用 dunder 方法,除非你真的了解它们在做什么。即使那样,最好还是避免它。
    通常不值得通过使用以下内容来试图变得可信或简洁:
    x.__lt__(y)
    代替:
    x < y
    你至少应该明白,这可能会发生:
    >>> (1).__lt__(3.)
    NotImplemented
    >>>
    如果你只是天真地做 filter((1).__lt__, iterable) 这样的事情那么你可能有一个错误。

    关于python - `in` 为生成器定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65150961/

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