gpt4 book ai didi

python - 如何通过值正确地将对象传递给函数

转载 作者:行者123 更新时间:2023-12-02 17:31:15 25 4
gpt4 key购买 nike

我有一个具有复杂参数的递归函数,例如数组和对象字典。
这是主要的递归函数

def finish_top_line(puzzle,result,corner,edge,results):
min_loss, min_index = 0, 0
loss_dic = {}
a_dict = {}
pieces = {}
i = len(list(result.keys()))
print(len(results)," : ",i)
if i == 1 or i == 25:
corner.remove(result[i - 1])
else:
edge.remove(result[i - 1])
if i == 25:
elif i == 24:
for index in corner:
find_corner(puzzle[index], 1,puzzle[result[i-1]])
result[i] = index
print("done with 24")
final = show_results(result, puzzle)
j = len(results)
r = ResultSet()
r.puzzle = puzzle
r.result = result
r.corners = corner
r.edges = edge
results.append(r)
name = "result"+ str(j) + ".png"
print(name)
final.save(name)
else:
for index in edge:
left_index = result[i - 1]
***important parts***
loss, a_diff, piece = match_left_right(puzzle[left_index].clone_piece(), puzzle[index].clone_piece())
pieces[index] = piece
loss_dic[loss] = index
if min_loss == 0 or loss < min_loss:
min_index = index
min_loss = loss

s = sorted(loss_dic.keys())
l = []
for j in s:
# p, r, c, e = 0,0,0,0
if abs(j - min_loss) <= LOSS_RANGE:
index = loss_dic[j]
print(index, " : ", j)
t = deepcopy(puzzle[index])
puzzle[index] = pieces[index]
result[i] = index
***important parts***
p, r, c, e = copyPuzzle(puzzle), deepcopy(result), deepcopy(corner), deepcopy(edge)
finish_top_line(puzzle, r ,c, e,results)

puzzle = p
puzzle[index] = t
else:
break

在这里有两个地方,我试图以某种方式处理对象,以避免对函数中的参数所做的更改影响到外部。

下面的函数是用来复制对象字典的函数。在这里,deepcopy无法正常工作。
def copyPuzzle(puzzle):
p = {}
for i in list(puzzle.keys()):
p[i] = (puzzle[i].clone_piece())
return p

这是编码在对象下的函数克隆函数。
def clone_piece(self):
t = Piece()
t.edge_type = deepcopy(self.edge_type)
t.corners = deepcopy(self.corners)
t.img = deepcopy(Image.fromarray(np.uint8(cv2.cvtColor(np.asarray(self.img), cv2.COLOR_RGB2BGR))))
t.edge_type = deepcopy(self.edge_type)
t.index= deepcopy(self.index)
t.floatCorners = deepcopy(self.floatCorners)
t =self
return t

对函数内部数据所做的更改就像旋转和调整图像大小一样。最后在测试时..数据似乎随着代码的进行变得混乱,并且可以清楚地看到每个保存的图像比以前的图像更混乱。因此,这种试图超越值(value)的尝试似乎行不通。我怎样才能解决这个问题?
如何正确地传递值

最佳答案

def clone_piece(self):
t = Piece()
t.edge_type = deepcopy(self.edge_type)
t.corners = deepcopy(self.corners)
t.img = deepcopy(Image.fromarray(np.uint8(cv2.cvtColor(np.asarray(self.img), cv2.COLOR_RGB2BGR))))
t.edge_type = deepcopy(self.edge_type)
t.index= deepcopy(self.index)
t.floatCorners = deepcopy(self.floatCorners)
t =self
return t

可以更改为
def clone_piece(self):
return deepcopy(self)

您犯的错误是返回之前的这一行:
t = self

这基本上是取消所有先前的行

关于python - 如何通过值正确地将对象传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55491572/

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