Matias
Matias

Reputation: 332

My __str__ is too long, best way to write it

I've this __str__ method in one of my classes but in my opinion it looks a bit too long in my code for python conventions and autopep is not giving me any hints.

So I was wondering what would be the most pythonic way to type it.

I need the break lines because solution and table shapes are 52 and 52x52 respectively.

def __str__(self):
    return "Cost solution : " + str(self.cost) + "\nSolution: " + str(self.solution) + "\n\nTable:" + str(self.table)

Upvotes: 3

Views: 2725

Answers (3)

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

Python 3.6 introduced f-strings, which allow for short strings & format

class foo:
  def __init__(self):
    self.cost = 12
    self.solution = "easy"
    self.table = "no"
  def __str__(self):
    return f"Cost: {self.cost}\nSolution: {self.solution}\nTable: {self.table}"

f = foo()
print(str(f))

Upvotes: 3

Prime Reaper
Prime Reaper

Reputation: 186

def __str__(self):
    pattern = '''
    Cost solution: {}
    Solution: {}
    Table: {}
    '''
    return pattern.format(self.cost, self.solution, self.table)

If you don't want extra tabs in output while using multiline strings you need to remove tabs in your code in them.

class Test(object):
    pattern = '''
Cost solution: {}
Solution: {}
Table: {}
'''
    def __init__(self):
        self.cost = 0;
        self.solution = 'StackOverflow'
        self.table = '1|2|3|4'

    def __str__(self):
        return self.pattern.format(self.cost, self.solution, self.table)

print Test()

Upvotes: 4

Alex Boxall
Alex Boxall

Reputation: 581

You can use the str.format method to combine strings in a more pythonic way, but it is still quite long.

def __str__(self):
    return "Cost solution: {}\nSolution: {}\n\nTable {}".format(self.cost, self.solution, self.table)

You can split it over two lines after the end of the format string if you need to by using the backward slash.

Upvotes: 1

Related Questions