[英]Override Python's 'in' operator?
If I am creating my own class in Python, what function should I define so as to allow the use of the in
operator, eg如果我在 Python 中创建自己的类,我应该定义什么函数以允许使用
in
运算符,例如
class MyClass(object):
...
m = MyClass()
if 54 in m:
...
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
:在这里,当询问 54 是否在
m
时,您会得到True
:
>>> m = MyClass()
>>> 54 in m
True
See documentation on overloading __contains__
.请参阅有关重载
__contains__
文档。
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/ http://code.activestate.com/recipes/384122/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.