当“按值传递”似乎仍在递归函数内更改原始对象时

时间:2019-05-09 14:29:24

标签: python

def paintPointsBlack(originalBoard, point0, point1, point2):
    board = originalBoard[:]
    # do something
    return board

def fillTheBoard(board, point):
    movePointToWhitePoint(board, point)   

    if point['row'] == height - 1:
        print('last line. terminate')
        return

    elif point['row'] != height - 1:
        LCanFit = canPutLShape(board, point)
        if LCanFit['total'] != 0:
            point0 = dict(point)
            if LCanFit['RdD'] == 1:
                ...
                newBoard = paintPointsBlack(board[:], point, point1, point2)
                fillTheBoard(newBoard, point0)
            if LCanFit['DL'] == 1:
                ...
                newBoard = paintPointsBlack(board[:], point, point1, point2)
                fillTheBoard(newBoard, point0)
            if LCanFit['RD'] == 1:
                ...
                newBoard = paintPointsBlack(board[:], point, point1, point2)
                fillTheBoard(newBoard, point0)
            if LCanFit['DR'] == 1:
                ...
                newBoard = paintPointsBlack(board[:], point, point1, point2)
                fillTheBoard(newBoard, point0)          
            print("inspected everything around : ", point['row'], point['col'])
        else:
            return

fillTheBoard是在某些条件(LCanFit)匹配时调用的函数。 if有很多,为了使其正常工作,初始传递的参数board不应在if的相同深度处改变。可能会更改board的唯一函数是paintPointsBlack,但为避免这种情况,我传递了副本(board[:]),并进行了一次谨慎但无意义的尝试,使它复制了参数在paintPointsBlack中。

我遇到的问题是,在递归的一个分支完成之后,board仍然会更改,并移至下一个分支(下一个if)。因此,board内的if LCanFit['RdD'] == 1board内的if LCanFit['DL'] == 1(相同的深度)是不同的,因为board更改为{{1}最后调用的函数(与前一个newBoard一起使用的最深函数)。

我知道按值传递无法更改原始内容,但我仍然看到它会更改if,而且如此令人困惑。如果我最好重写代码,应该如何构造它?

0 个答案:

没有答案