0

Is it possible to return the string representation (using __str__) of all objects in a list of objects from a different classes own __str__ function?

Say I have a class that contains all methods being performed on Bar objects. Call this class Foo. Then:

class Foo:
    def __init__(self):
        self.bars = []  # contains Bar objects

    def __str__(self):
        return "This is the Foo object"

class Bar:
    def __init__(self, arg1):
        self.arg1 = arg1

    def __str__(self):
        return "This is Bar object: " + arg1

def main():
    foo = Foo()
    print(str(foo))

I want to print the string representation of all of the objects in self.bars WHEN I call main(), since creating an instance of the Bar object would not give me access to the string representation of all of the objects in self.bars.

To clarify, I am not asking the same question as in this post relating to the need of __repr__. Instead, I want to return each object's string representation individually, as with a for loop.

Is there anyway to do this, reasonably or unreasonably?

Community
  • 1
  • 1
kmartmvp
  • 57
  • 2
  • 8
  • Do you mean something like `return ','.join(str(b) for b in self.bars)`? – mgilson Apr 22 '16 at 00:17
  • Also, if I AM asking the same question as the link I posted, then feel free to correct me. If this is a duplicate in some sense of the word, then it is just because of my misunderstanding of the subject matter. – kmartmvp Apr 22 '16 at 00:17

1 Answers1

0

You already said how to do this, use a for loop.

return "".join([str(x) + "\n" for x in self.bars])
Natecat
  • 2,175
  • 1
  • 17
  • 20
  • You can't return a `list` from `__str__`. Perhaps `'\n'.join(map(str, self.bars))` or the list-comprehension equivalent... – mgilson Apr 22 '16 at 00:18
  • @Natecat The real problem here seems to be that __str__ cannot return a list, or a tuple. In this case, attempting multiple elements such as `return ("This is the Foo object", ".join([str(x) + "\n" for x in self.bars]))` does not work, as it returns a tuple. Unless I'm mistaken, in Python all functions that return multiple elements return as a tuple and must be unzipped? It should be easy to edit the return statement to work, but this might not work in all cases. – kmartmvp Apr 22 '16 at 00:36