1

I want to create switch case, but don't know how to call one function from another. For example, in this code I want to call OrderModule() when I press "O".

Actually I've already done whole program in Java, maybe somebody know, how to convert it more easily without re-writing it all?

class CMS:

    def MainMenu():
        print("|----Welcome to Catering Management System----|")

        print("|[O]Order")
        print("|[R]Report")
        print("|[P]Payment")
        print("|[E]Exit")
        print("|")
        print("|----Select module---- \n")
        moduleSelect = raw_input()
        if moduleSelect == "o" or moduleSelect == "O":
            ---
        if moduleSelect == "r" or moduleSelect == "R":
            ---
        if moduleSelect == "P" or moduleSelect == "P":
            ---
        if moduleSelect == "e" or moduleSelect == "E":
            ---
        else:
            print("Error")
    MainMenu()
    def OrderModule():
        print("|[F]Place orders for food")
        print("|[S]Place orders for other services")
        print("|[M]Return to Main Menu")
    OrderModule()
6
  • Are you asking how to call a function? Commented Dec 18, 2016 at 16:49
  • Yes, like method in java Commented Dec 18, 2016 at 16:58
  • 'self' is the keyword in Python, and it should be explicitly passed as a first method's argument. Also, this code could be rewritten using Strategy design pattern. Commented Dec 18, 2016 at 17:27
  • I read about 'self', but when apply it, get message name 'self' is not defined Commented Dec 18, 2016 at 17:35
  • @KidBinary self is not a keyword, it's just a convention that first argument to instance method is self (and first argument to classmethod is cls). Commented Dec 19, 2016 at 10:01

1 Answer 1

1

Here's the deal. I'll refactor the code a bit for the sake of your understanding of Python and maybe some good tip about design patterns.

Please, consider this example over-simplified and somewhat excessive, it's done with singular purpose to boost your emerging development skills.

First, it's good to familiarize yourself with Strategy Design Pattern, which comes in handy for such tasks (in my personal opinion). After that you can create a base module class and it's strategies. Notice how self (variable that represents the instance of the object itself) explicitly passed as a first argument to classes methods:

class SystemModule():
    strategy = None

    def __init__(self, strategy=None):
        '''
        Strategies of this base class should not be created
        as stand-alone instances (don't do it in real-world!).
        Instantiate base class with strategy of your choosing
        '''
        if type(self) is not SystemModule:
            raise Exception("Strategy cannot be instantiated by itself!")
        if strategy:
            self.strategy = strategy()

    def show_menu(self):
        '''
        Except, if method is called without applied strategy
        '''
        if self.strategy:
            self.strategy.show_menu()
        else:
            raise NotImplementedError('No strategy applied!')


class OrderModule(SystemModule):
    def show_menu(self):
        '''
        Strings joined by new line are more elegant
        than multiple `print` statements
        '''
        print('\n'.join([
            "|[F]Place orders for food",
            "|[S]Place orders for other services",
            "|[M]Return to Main Menu",
        ]))


class ReportModule(SystemModule):
    def show_menu(self):
        print('---')


class PaymentModule(SystemModule):
    def show_menu(self):
        print('---')

Here OrderModule, ReportModule and PaymentModule can be defined as first-class functions, but classes are more obvious for this example. Next, create a main class of your application:

class CMS():
    '''
    Options presented as dictionary items to avoid ugly
    multiple `if-elif` construction
    '''
    MAIN_MENU_OPTIONS = {
        'o': OrderModule, 'r': ReportModule, 'p': PaymentModule,
    }

    def main_menu(self):
        print('\n'.join([
            "|----Welcome to Catering Management System----|", "|",
            "|[O]Order", "|[R]Report", "|[P]Payment", "|[E]Exit",
            "|", "|----Select module----",
        ]))

        # `raw_input` renamed to `input` in Python 3,
        # so use `raw_input()` for second version. Also,
        # `lower()` is used to eliminate case-sensitive
        # checks you had.
        module_select = input().lower()

        # If user selected exit, be sure to close app
        # straight away, without further unnecessary processing 
        if module_select == 'e':
            print('Goodbye!')
            import sys
            sys.exit(0)

        # Perform dictionary lookup for entered key, and set that
        # key's value as desired strategy for `SystemModule` class
        if module_select in self.MAIN_MENU_OPTIONS:
            strategy = SystemModule(
                strategy=self.MAIN_MENU_OPTIONS[module_select])

            # Base class calls appropriate method of strategy class
            return strategy.show_menu()
        else:
            print('Please, select a correct module')

For this whole thing to work, there's a simple starter at the end of file:

if __name__ == "__main__":
    cms = CMS()
    cms.main_menu()

Here you go. I really hope that this snippet will help you to dive deeper into Python : ) Cheers!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.