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

2024-04-20 04:17:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建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()

Tags: orto函数forifdefplacecase
1条回答
网友
1楼 · 发布于 2024-04-20 04:17:17

就这么定了。为了您对Python的理解,以及一些关于设计模式的好提示,我将对代码进行一些重构。你知道吗

请考虑一下这个例子过于简单,有些过分,它的目的是为了提高你的新兴开发技能。你知道吗

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

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:) 干杯!你知道吗

相关问题 更多 >