2016-12-18 15 views
1

私はスイッチケースを作成したいが、ある機能を別の機能から呼び出す方法はわからない。例えば、このコードでは、 "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() 
+0

関数を呼び出す方法を尋ねていますか? – Carcigenicate

+0

はい、javaのメソッドと同じです –

+0

'self'はPythonのキーワードであり、最初のメソッドの引数として明示的に渡す必要があります。また、このコードは戦略設計パターンを使用して書き換えることができます。 – Nevertheless

答えて

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に深く浸るのを助けることを本当に願っています:) 乾杯!

関連する問題