theButcher
theButcher

Reputation: 75

Recall menu within cmd module python

I am making making a commandline program using python's cmd module. In this program I use numbers in order to determine what feature the user want to use. I have the following issue for feature 6 which is simply printing out the features again but I want to recall the MainMenu class so I don't have to use:

def do_6(self, line):
        print ("   M A I N - M E N U")
        print ("1. Feature one")
        print ("2. Feature two")
        print ("3. Feature three")
        print ("4. Feature four")
        print ("5. Feature five")
        print ("6. Print options")
        print ("7. Exit ")
        print (30 * '-')

Which is simply just repeating what is in the MainMenu class but is a bit sloppy if you want to change the MainMenu. You are forced to also change feature 6.

MainMenu class:

class MainMenu(cmd.Cmd):
    print ("   M A I N - M E N U")
    print ("1. Feature one")
    print ("2. Feature two")
    print ("3. Feature three")
    print ("4. Feature four")
    print ("5. Feature five")
    print ("6. Print options")
    print ("7. Exit ")
    print (30 * '-')

I tried doing this:

def do_6(self, line):
        MainMenu()

or

def do_6(self, line):
        MainMenu

But this has no effect, how do I recall my MainMenu class properly? My second question is: Let's say I want to recall the MainMenu class everytime a feature has ended or completed, how do I do this?

Upvotes: 1

Views: 92

Answers (1)

FunkySayu
FunkySayu

Reputation: 8061

class MainMenu(cmd.Cmd):

    def __init__(self):
        """ Class constructor """

        print ("   M A I N - M E N U")
        print ("1. Feature one")
        print ("2. Feature two")
        print ("3. Feature three")
        print ("4. Feature four")
        print ("5. Feature five")
        print ("6. Print options")
        print ("7. Exit ")
        print (30 * '-')

You need to understand how class works. Classes have members, methods and many other features. As in all the languages, you need to define this fields. For example, here is a method with a constructor, a field and a method :

class Example:

    field = "foo"

    def __init__(self, ivar_value):
        self.instance_var = ivar_value

    def print_me(self):
        print("Field : ", self.field)
        print("Var   : ", self.instance_var)

Classes are only defined once. And when you tryied to run the MainMenu() with your way to do it, it would work only one time because the second time, the class MainMenu was already defined.

Upvotes: 1

Related Questions