Python Forum
Magic method __str__ - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Magic method __str__ (/thread-14812.html)

Pages: 1 2


RE: Magic method __str__ - dan789 - Dec-19-2018

@nilamo no, I don´t want to copy a list inside a function, all what I need is this function should work for changes in a list. For example, after __init__ (which creates a list self.tab) I want __str__() to create a string from this list. Using the code by @buran few posts above it works, but I need to call this method also later, after some changes in this self.tab happen. And these are specifically "." changed to a set. After this, method __str__() create a string consisting of numbers and sets, but I still want to put "." instead of sets here.


RE: Magic method __str__ - dan789 - Dec-22-2018

UP....


RE: Magic method __str__ - ichabod801 - Dec-22-2018

def __str__(self):
    lines = []
    for sub_list in self.tab:
        lines.append(' '.join([str(item) for item in sub_list if not isinstance(item, set) else '.']))
    return '\n'.join(lines)



RE: Magic method __str__ - dan789 - Dec-22-2018

This raises me an invalid syntax error and not sure what is wrong there.. :/


RE: Magic method __str__ - ichabod801 - Dec-22-2018

Sorry, that should be:

def __str__(self):
    lines = []
    for sub_list in self.tab:
        lines.append(' '.join([str(item) if not isinstance(item, set) else '.' for item in sub_list]))
    return '\n'.join(lines)



RE: Magic method __str__ - dan789 - Dec-23-2018

@ichabod801 thanks, this seems working, the only thing missing (I forgot to mentioned that, but I guess it´s just an addition into this generator notation) - if length of set is 1, it should put that one item (number) into that string, instead of "."
Is it possible to add "elif" statement there?


RE: Magic method __str__ - ichabod801 - Dec-23-2018

No, you can't put an elif in a ternary statement. You would have to break that list comprehension out into a loop with a full conditional statement.