【问题标题】:How does "contains" work? Does it use iter and getitem?“包含”如何工作?它使用iter和getitem吗?
【发布时间】:2020-12-03 17:25:37
【问题描述】:

__contains__ 是如何工作的?例如,我有一个类MyClass 和一个名为a 的类的实例,当我写if val in a: 时,我基本上是在调用__contains__,根据我的理解,如果__contains__ 没有在类中实现,那么调用__iter__,它在__getitem__(在我的示例中在类中实现)返回的列表之间进行迭代,如果val 等于列表中的某个元素,则__contains__ 返回True。对吗?

编辑:我的代码中的__getitem__ 仅返回给定位置的列表元素,所以我不知道它如何与__iter__ 一起使用

【问题讨论】:

标签: python


【解决方案1】:

我觉得__contains__的文档已经够清楚了,

> Called to implement membership test operators. Should return true if
> item is in self, false otherwise. For mapping objects, this should
> consider the keys of the mapping rather than the values or the
> key-item pairs.
> 
> 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.

【讨论】:

  • “如果 item 在 self 中,则应返回 true”,因此它会检查类实例的每个属性,如果发现一个属性的值为“val”,则返回 true?
  • 我认为它不会检查对象属性(或者它的字典)。 (x.a) x有一个属性a,不代表a in x
  • 大约 in 只有在对象可以被视为容器类(字典、序列等)时才有意义(已定义)。
  • 按字典我的意思是__dict__
【解决方案2】:

完全正确。更多细节here:

对于定义 contains() 方法的用户定义类,x in 如果 y.contains(x) 返回真值,则 y 返回 True,而 False 否则。

对于没有定义 contains() 但确实 定义 iter(), x in y is True if some value z, for which the 表达式 x 为 z 或 x == z 为真,在迭代时产生 是的。如果在迭代过程中引发异常,就好像在 引发了该异常。

最后,尝试旧式迭代协议:如果一个类定义 getitem(), x in y 为 True 当且仅当存在一个非负整数索引 i 使得 x 为 y[i] 或 x == y[i],并且没有更低的整数 index 引发 IndexError 异常。 (如果有任何其他例外情况 引发,就好像引发了那个异常)。

【讨论】:

  • 如果只实现了“getitem”,当我调用“contains”时,它是否也使用了“len " 知道可能的最大指数吗?否则,我不知道程序将如何停止
  • 不确定你指的是什么'因为“你”写了“真”'。但是,我并没有试图剽窃或声明这些信息,而是从文档中列出了这里的信息。该链接未正确包含。它现在就在那里。
  • 我明白了。好吧,我确实在我所有的写作中都说真/假。但是感谢您指出这一点——我一定会确保一切都得到适当的认可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2011-11-08
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
相关资源
最近更新 更多