1

I'm trying to make an object which behaves like a string when it is used in "x in y" syntax.

For example, in this case, I want my object "test" behave like the string "ABCDEFG" when I compare it to another string. I think this should be done in the iter function but it doesn't seem to work.

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
ninhenzo64
  • 702
  • 1
  • 9
  • 23

1 Answers1

2

You want to overload the __contains__ special method to control the behavior of in with your class:

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

The __iter__ special method (which you should still overload for a custom string type) is for producing an iterator over a container class. In other words, it makes your class iterable:

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