1

consider following method in a class

def printlist(self):
    traverser = self.head
    while traverser.next:
        print(traverser.val, end=", ")
        traverser = traverser.next
    else:
        print(traverser.val)

this method is returning None but printing something (like 1, 2, 3) . My goal is to get as string which is printed by printlist method so that it could be used to return string representation of object as follows

def __str__(self):
   str_output = some_magic(self.printlist())
   return str_output
karansthr
  • 331
  • 2
  • 8

1 Answers1

0

Currently your function is expected to do two things: find the values and construct (and print) the string. Functions should try and do one thing.

Use two separate functions.

For the values just use recursion:

def list_values(traverser):
    # yield all values from the linked list
    yield traverser.val
    if traverser.next:
        yield from list_values(traverser.next)

For constructing the string there is a built-in:

expected = ', '.join(some_magic(traverser))
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88