Override Python's 'in' operator?

空扰寡人 提交于 2019-11-26 03:51:38

问题


If I am creating my own class in Python, what function should I define so as to allow the use of the \'in\' operator, e.g.

class MyClass(object):
    ...

m = MyClass()

if 54 in m:
    ...

回答1:


MyClass.__contains__(self, item)




回答2:


A more complete answer is:

class MyClass(object):

    def __init__(self):
        self.numbers = [1,2,3,4,54]

    def __contains__(self, key):
        return key in self.numbers

Here you would get True when asking if 54 was in m:

>>> m = MyClass()
>>> 54 in m
True  

See documentation on overloading __contains__.




回答3:


You might also want to take a look at an infix operator override framework I was able to use to create a domain-specific language:

http://code.activestate.com/recipes/384122/



来源:https://stackoverflow.com/questions/2217001/override-pythons-in-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!