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”
1
  • @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, 2020 at 16:55

1 Answer 1

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
1
  • 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. Oct 12, 2020 at 17:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.