如何在 python 中的 class 中正确实现辅助函数

How to properly implement helper functions in a class in python

我是 python 的新手,我正在尝试设计一个 class 来解决 N 皇后问题。 这是我的 class def:

class QueenSolver:

    def genEmptyBoard(self, n):
        # Generates an empty board of n width and n height
        board = []
        for _ in range(n):
            board.append([0 for _ in range(n)])
        return board

    def genLegalBoard(self, q1, q2, n):
        # Returns legal board or false
        board = self.genEmptyBoard(self, n)
        try:
            board[q1[0]][q1[1]] = 'q'
        except IndexError:
            print("Queen placed outside of board constraints")
            return False
        try:
            if board[q2[0]][q2[1]] == 'q':
                print("Queens cannot be placed in the same position")
                return False
            board[q2[0]][q2[1]] = 'Q'
        except IndexError:
            print("Queen placed outside of board constraints")
            return False 
        return board

但是,当我在 class 之外调用此方法时,如下所示:

board = QueenSolver.genLegalBoard([0, 0], [7, 7], 8)

我收到如下所示的错误:

Exception has occurred: TypeError
QueenSolver.genLegalBoard() missing 1 required positional argument: 'n'

显然,当从 class 定义之外调用它时,我必须提供“self”变量?我认为“self”参数不需要任何值,因为它是假定的?我在这里错过了什么?

在调用class的方法之前,您需要实例化QueenSolverclass的一个对象。此外,从 board = self.genEmptyBoard(self, n).

中删除 self
class QueenSolver:

    def genEmptyBoard(self, n):
        # Generates an empty board of n width and n height
        board = []
        for _ in range(n):
            board.append([0 for _ in range(n)])
        return board

    def genLegalBoard(self, q1, q2, n):
        # Returns legal board or false
        board = self.genEmptyBoard(n)

        ............
        ............

        return board

QS = QueenSolver()
board = QS.genLegalBoard([0, 0], [7, 7], 8)

输出:

[['q', 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 'Q']]