问题:重写Python的“ in”运算符?

如果要在Python中创建自己的类,则应定义什么函数,以便允许使用“ in”运算符,例如

class MyClass(object):
    ...

m = MyClass()

if 54 in m:
    ...

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:
    ...

回答 0


回答 1

一个更完整的答案是:

class MyClass(object):

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

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

在这里,当问54是否在m中时,您将得到True:

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

请参阅有关重载的文档__contains__

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__.


回答 2

您可能还想看一下我用来创建特定于域的语言的中缀运算符覆盖框架:

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

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/


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。