如何在python的类中正确实现辅助函数
Posted
技术标签:
【中文标题】如何在python的类中正确实现辅助函数【英文标题】:How to properly implement helper functions in a class in python 【发布时间】:2022-01-16 16:15:59 【问题描述】:我对 python 还很陌生,我正在尝试设计一个类来解决 N 皇后问题。 这是我的班级定义:
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
但是,当我在类之外调用这个方法时,像这样:
board = QueenSolver.genLegalBoard([0, 0], [7, 7], 8)
我收到如下所示的错误:
Exception has occurred: TypeError
QueenSolver.genLegalBoard() missing 1 required positional argument: 'n'
显然我必须在从类定义外部调用“self”变量时提供它?我认为“self”参数不需要任何值,因为它是假设的?我在这里错过了什么?
【问题讨论】:
你的意思是正确而不是可能吗? 【参考方案1】:在调用类的方法之前,需要先实例化QueenSolver
类的对象。同时,从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']]
【讨论】:
以上是关于如何在python的类中正确实现辅助函数的主要内容,如果未能解决你的问题,请参考以下文章
如何在struct中正确定义一个函数指针,它以struct为指针?