我在
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()成为类的正确方法?