我在
Python 2.7中編寫了一些Python代碼,我在另一個函數中調用函數表時遇到問題.
class CSP:
def __init__(self, matrix):
self.X = []
self.D = []
self.C = []
self.matrix = util.copyMatrix(matrix)
self.counter = 0
# Matrix to Vector
vector = [item for line in self.matrix for item in line]
chars = map(str, vector)
result = ['*' if item == '0' else item for item in chars]
def solve(self):
""" Returns the result matrix.
The sudoku matrix is self.matrix.
Use util.printMatrix in purpose of debugging if needed. """
"*** YOUR CODE HERE ***"
def init(self,result):
for i in range(9):
for j in range(1,10):
var = var_char[i]+str(j)
self.X.append(var)
domain = set([1,2,3,4,5,6,7,8,9])
self.D.append(domain)
gamelist = result
for i in range(len(gamelist)):
if(re.match("\d+",gamelist[i])):
self.D[i] = set([int(gamelist[i])])
self.set_constraints()
#########################################################################
def set_constraints(self):
for x in self.X:
for y in self.X:
if((x[0] == y[0] and x[1] != y[1]) or (x[1] == y[1] and x[0] != y[0])):
flag = True
for c in self.C:
if(x in c and y in c):
flag = False
if(flag):
self.C.append(set([x,y]))
for a in [0,3,6]:
for b in [0,3,6]:
self.set_cube_constraints(a,b)
如何在solve()中調用init()函數并在init()函數中調用self.set_constraint()?
最佳答案 在函數solve()中,init()是一個函數,而不是一個方法.是以,隻能以與調用任何其他未綁定函數相同的方式調用它:通過向其傳遞正确數量的參數.這可行:
init(self, results)
請注意,您需要在self中顯式傳遞對象的引用,因為init()不是方法.在solve()中,self指的是CSP執行個體,是以這應該有效.
但是,set_constraints()也是一個普通的函數,是以你不能使用self.set_constraints()從init()調用它,但是set_constraints(self)應該可以工作.請注意,您需要在init()之前聲明函數set_constraints(),否則您将獲得“在指派前引用”錯誤.
說了這麼多,這太可怕了.為什麼不使init()和set_constraints()成為類的正确方法?