使对象支持“in”

时间:2014-08-26 11:16:56

标签: python

我有一个名为“GenomicLocation”的对象类型。我想支持该对象的“in”操作,以便我可以编写

genomic_location1 in genomic_location2

如果满足某些条件。

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

1 个答案:

答案 0 :(得分:4)

您应该定义方法

__contains__

示例:

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