【问题标题】:If I have a function does basically the same thing as another, what would be the best way to join them?如果我有一个功能与另一个功能基本相同,那么加入它们的最佳方式是什么?
【发布时间】:2020-10-05 05:50:15
【问题描述】:

我有一个显示战舰游戏“棋盘”的功能。然后是另一个功能,显示相同的板,但隐藏其中有船的地点(以免将它们交给用户)。代码是:

def display(self):

       os.system("cls")
       print("Displaying {} grid \n".format(self.name)) 

       i = 0 #this block prints column numbers
       print("O", end="  ")
       for h in range(1,10+1):
           print(h,end="   ")
       print("\n")

       while i < 10: #this block prints row letters and board
           print(chr(i+65), end= "  ")
           row = self.board[i]
           for j in row:
               print(j, end="   ")
           i += 1
           print("\n") 


   def hide (self):
       os.system("cls")
       print("Displaying {} grid \n".format(self.name)) 

       i = 0 #this block prints column numbers
       print("O", end="  ")
       for h in range(1,10+1):
           print(h,end="   ")
       print("\n")

       while i < 10: #this block prints row letters and board
           print(chr(i+65), end= "  ")
           row = self.board[i]
           for j in row:
               if j == self.aboathere:
                   print(self.noboat, end="   ")   
               else:
                   print(j, end="   ")
           i += 1
           print("\n") 

在hide中“for j in row”下面的if结构略有不同,但功能基本相同。它工作正常,但似乎有点多余。如何改进?

【问题讨论】:

    标签: python python-3.x refactoring code-reuse


    【解决方案1】:

    最简单的解决方案可能是在您的函数中添加一个开关参数,该参数将显示/隐藏船只:

    def show_board(self, show_boats=False):
        os.system("cls")
        print("Displaying {} grid \n".format(self.name))
    
        i = 0  # this block prints column numbers
        print("O", end="  ")
        for h in range(1, 10 + 1):
            print(h, end="   ")
        print("\n")
    
        while i < 10:  # this block prints row letters and board
            print(chr(i + 65), end="  ")
            row = self.board[i]
            for j in row:
                if j == self.aboathere:
                    print(j if show_boats else self.noboat, end="   ")
                else:
                    print(j, end="   ")
                    
            i += 1
            print("\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-18
      • 1970-01-01
      • 2020-07-26
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多