gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:49 30 4
gpt4 key购买 nike

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

最佳答案

这是交易。为了让您理解 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 :)干杯!

关于python - 如何从类中的另一个函数(方法)调用一个函数(方法)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210610/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com