0

what should I do when I would like to return object from class and at the same time can print this result.

I did this:

class Engine:
    def __init__(self, mylist):
        self._mylist = list(mylist)

    def __str__(self) -> str:
        return ','.join(el.__str__() for el in self._mylist)

    def __repr__(self):
        return self._mylist

but when I do:

p = Engine(lst)
print(p)

for x in p:
   print("Element", x)

I get:

element1, element2, element3
TypeError: 'Engine' object is not iterable

What should I do to have possibility to print this result and also iterate over it just like the object?

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
Mlody87
  • 425
  • 1
  • 7
  • 19

1 Answers1

2

You can refer to one of the class variables for this to work. By default, you can't iterate over an entire object. The proper way would be to iterate through the list you passed, which is now an object variable. It works if you run:

lst = [1, 2, 3, 4, 5]

p = Engine(lst)

print(p)

for ix in p._mylist:
   print("Element", ix)

But I'm guessing you're seeking another solution because you named the list _mylist, which generally means that this variable is not supposed to be accessed from the outside.

Therefore, you can instead turn the object itself into an iterable. For this, you need to define the __iter__ dunder method, and define it's behavior when you treat it as an iterator.

    def __iter__(self):
        return iter(self._mylist)
class Engine:
    def __init__(self, mylist):
        self._mylist = list(mylist)

    def __str__(self) -> str:
        return ','.join(el.__str__() for el in self._mylist)

    def __repr__(self):
        return self._mylist

    def __iter__(self):
        return iter(self._mylist)

lst = [1, 2, 3, 4, 5]

p = Engine(lst)

print(p)

for ix in p:
   print("Element", ix)
1,2,3,4,5
Element 1
Element 2
Element 3
Element 4
Element 5
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143