0

How can I add method, which allowed to use in With my class aa?

class aa:
    def __init__(self,x):
        self.x=x
    def __str__(self):
        return str(self.x)
    def __add__(self,other):
        x=self.x+other
        return aa(x)

a=aa(2)
print(2 in a) # error: “...arg not iterable”
Timur U
  • 415
  • 2
  • 14
  • @jpp, the one about iterators is not a duplicate as it is not what OP is asking about (you can't us `in` with iterators) – Tomerikoo Oct 12 '20 at 16:55

1 Answers1

2

You need to implement __contains__ for you class.

See more here.

class aa:
    def __init__(self,x):
        self.x=x
    def __str__(self):
        return str(self.x)
    def __add__(self,other):
        x=self.x+other
        return aa(x)
    def __contains__(self,x):
        # TODO implement  
        pass
balderman
  • 22,927
  • 7
  • 34
  • 52
  • Though it is not required, it is a good idea for a class that you intend to use as a container be a subclass of `collections.abc.Container`. Your readers and your IDE will better understand your intent. In addition, Python will give you an error if you forget to define `__contains__` or accidentally. misspell it. – Frank Yellin Oct 12 '20 at 17:01