如何在一个类中调用另一个函数(方法)?

时间:2016-12-18 16:48:26

标签: python function

我想创建switch case,但不知道如何从另一个函数调用一个函数。例如,在此代码中,我想在按“O”时调用OrderModule()

实际上我已经用Java完成了整个程序,也许有人知道,如何在不重写的情况下更轻松地转换它?

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()

1 个答案:

答案 0 :(得分:1)

这是这笔交易。为了理解Python,我会稍微重构代码,也许还有一些关于设计模式的好建议。

请注意,这个例子过于简化并且有点过分,它的目的是为了提高你的新兴开发技能。

首先,熟悉Strategy Design Pattern很有用,这对于此类任务非常有用(在我个人看来)。之后,您可以创建基本模块类及其策略。 注意self(表示对象本身实例的变量)如何作为第一个参数显式传递给类方法

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('---')

此处OrderModuleReportModulePaymentModule可以定义为第一类函数,但对于此示例,类更明显。接下来,创建一个申请的主要类别:

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')

要完成整个工作,文件末尾有一个简单的启动器:

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

你走了。我真的希望这段代码能帮助你深入了解Python :) 干杯!