【问题标题】:Make objects support "in" [duplicate]使对象支持“in” [重复]
【发布时间】:2014-10-19 16:50:39
【问题描述】:

我有一种名为“GenomicLocation”的对象。我想支持那个对象的“in”操作,这样我就可以写了

genomic_location1 in genomic_location2

如果满足某些条件。

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

【问题讨论】:

标签: python


【解决方案1】:

你应该定义方法

__contains__

例子:

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

【讨论】:

    猜你喜欢
    • 2013-01-09
    • 2016-11-30
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多