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

标签 python function python-2.7

我在下面有一些用 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/

相关文章:

python - BOTO3使用Python获取EC2列表信息

javascript - 如何将这两个按钮功能合并为一个,例如开/关开关

function - 使用 defun 以编程方式构建 Common Lisp 函数

python - 这个组合器有名字吗?

python - 对字典中的值执行标准偏差

python - 用于手机的远程蓝牙摄像头触发器

python - 具有 2 个 m2m 关系的数据库设计

python - 如何重命名文件夹中的文件列表

python - 在 python 中,如何打印不包含特定字符串的行,而不是打印包含特定字符串 : 的行

python - 为什么导入模块会破坏我的 doctest (Python 2.7)