如果我有一个功能与另一个功能基本相同,加入它们的最佳方式是什么?

If I have a function does basically the same thing as another, what would be the best way to join them?

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

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结构,但基本是一样的功能。它工作正常但似乎有点多余。如何改进?

最简单的解决方案可能是向您的函数添加一个开关参数,这将 show/hide 船:

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