使对象支持"in"

  • 本文关键字:in 支持 对象 python
  • 更新时间 :
  • 英文 :


我有一个名为"GenomicLocation"的对象类型。我想支持该对象的操作"in",这样我就可以编写

genomic_location1 in genomic_location2

如果满足某些条件。

这可能吗?如果是,我该怎么做?

您应该定义方法

__contains__

示例:

>>> class Thing(object):
...     def __contains__(self, x):
...         return x == 'potato'
...     
>>> t = Thing()
>>> 'potato' in t
True
>>> 'spam' in t
False

最新更新