I’m writing a small program that prints a menu screen with a list of options. If you choose one of the options, the screen is cleared and you’re taken to the next menu.
Right now, I’ve made a base Menu class and given it a method draw() which draws the options. I then want to add a another method handle_options() which takes user input and then whisks the user off to the appropriate choice.
At the moment, I am creating a series of subclasses like class MainMenu(Menu) and class OptionsMenu(Menu). When handle_options() is looping, I’ll create an instance of the appropriate Menu class, and draw it, then loop into option choices.
But the thing is, I don’t want to have to define this handle_options() method for each variant of Menu. So I ask:
a) Is there a design pattern or better way of doing this kind of thing I can learn from?
b) Can I use something like getattr(self, "myfunc")() to call a function name I have stored in an array, so I can genericise the handle_options() method and define it in the base Menu class, rather than for each subclass?
tl;dr – What kinds of examples or patterns can be used to build a simple text-based menu system?
An alternative to defining
handle_optionsfor every subclass ofMenuis to define a dict that maps an option to a function call:Now your subclasses simply have to redefine
self._optionsand provide the appropriate methods associated with each option:You can also expand on
self._optionsto provide text description, for example, so your draw function can simply iterate through the options printing each one. Take a look at how to use argparse to infer a good design.