[英]How to probably implement helper functions in a class in python
我對 python 相當陌生,我正在嘗試設計一個 class 來解決 N 皇后問題。 這是我的 class 定義:
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 的方法之前,您需要實例化一個 QueenSolver QueenSolver
的 object。 以及,從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)
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
QS = QueenSolver()
board = QS.genLegalBoard([0, 0], [7, 7], 8)
Output:
[['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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.