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?
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:
If you are creating an attribute called options in __init__, it will shadow the class level attribute options, when you access it with self.
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[:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With