4

I have a class Menu

class Menu:

    options = []
    label = 'empty'

    def __init__(self, label, options):
        self.label = label
        self.options = options

    def __repr__(self):
        return '%s \n=====================\n\n%s' % (self.label, self.options[0])

What I am trying to do here is format the repr function so that it prints all the options. Right now it will correctly print

Label

\==============

Option 1

But can I throw a for loop in that return statement, or is there a proper way of fixing this?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Thustra
  • 67
  • 1
  • 6

1 Answers1

4

You can join all the values in the list, with str.join function and return it like this

return "{}\n=======\n\nOptions :[{}]".format(self.label, ", ".join(self.options))

Note:

  1. If you are creating an attribute called options in __init__, it will shadow the class level attribute options, when you access it with self.

  2. self.options = options will not create a new list when you assign. It will make both self.options and options refer the same list object passed. So, if you change self.options, it will be reflected in options as well. If you want to make a copy, you can use slicing like this self.options = options[:]

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • What is the main difference between the %s approach and the .format approach ? And yes I'll need to look into how classes actually work – Thustra Mar 20 '15 at 11:29
  • @Thustra You might want to check [this](http://stackoverflow.com/q/5082452/1903116) to know more about `format` and `%` syntax differences. – thefourtheye Mar 20 '15 at 11:34
  • I'll accept it I went with this for now to create the options list, to add some numbers. `option_list = '\n'.join([str(self.options.index(option) + 1) + '. ' + option for option in self.options])` And then I give that as the second parameter for format() – Thustra Mar 20 '15 at 11:48