gpt4 book ai didi

python - Python内部函数的调用函数

转载 作者:太空宇宙 更新时间:2023-11-03 11:27:55 25 4
gpt4 key购买 nike

我在下面有一些用 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() 是一个函数,而不是一个方法。因此,它只能以与调用任何其他未绑定(bind)函数相同的方式调用:通过将正确数量的参数传递给它。这会起作用:

init(self, results)

请注意,您需要在 self 中显式传递对对象的引用,因为 init() 不是方法。在 solve() 中,self 指的是 CSP 实例,所以这应该有效。

但是,set_constraints() 也是一个普通函数,因此您不能从 init() 中使用 self.set_constraints() 调用它>,但 set_constraints(self) 应该有效。请注意,您需要在 set_constraints() init() 之前声明函数,否则您将收到“赋值前引用”错误。

说了这么多,这太糟糕了。为什么不使 init()set_constraints() 成为类的正确方法?

关于python - Python内部函数的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30301960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com