Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a list in __repr__ function?

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?

like image 274
Thustra Avatar asked Oct 29 '25 16:10

Thustra


1 Answers

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[:]

like image 143
thefourtheye Avatar answered Oct 31 '25 06:10

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!