我正在尝试创建一个在“x in y”语法中使用时表现得像字符串的对象。
例如,在这种情况下,当我将其与另一个字符串进行比较时,我希望我的对象“test”的行为类似于字符串“ABCDEFG”。我认为这应该在 iter 函数中完成,但它似乎不起作用。
class Test(object):
def __init__(self, var):
self.var = var
def __iter__(self):
return iter(self.var)
>>> test = Test("ABCDEFG")
>>> print "EF" in test # I want this to return True
False
>>> print "EF" in "ABCDEFG" # this is how test should behave
True
答案 0 :(得分:1)
您希望重载__contains__
特殊方法以控制in
与您的班级的行为:
>>> class Test(object):
... def __init__(self, var):
... self.var = var
...
... def __contains__(self, substr):
... return substr in self.var
...
>>> test = Test("ABCDEFG")
>>> print "EF" in test
True
>>> print "YZ" in test
False
>>>
__iter__
特殊方法(您应该为自定义字符串类型重载)是用于在容器类上生成迭代器。换句话说,它使您的类可迭代:
>>> class Test(object):
... def __init__(self, var):
... self.var = var
...
... def __contains__(self, substr):
... return substr in self.var
...
... def __iter__(self):
... return iter(self.var)
...
>>> test = Test("ABCDEFG")
>>> for i in test: print i # This works because of Test.__iter__
...
A
B
C
D
E
F
G
>>>