gpt4 book ai didi

python - 为什么我的实例会发生变化?

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:13 26 4
gpt4 key购买 nike

<分区>

我正在制作一类由字典表示的多项式对象:

3*x^2+x+2 == {2:3, 1:1, 0:2}

这是我的代码中与问题相关的部分:

class Sparse_polynomial():
def __init__(self, coeffs_dict):
self.coeffs_dict = coeffs_dict


def __repr__(self):
terms = [" + ("+str(self.coeffs_dict[k])+"*x^" + str(k)+")" \
for k in sorted(self.coeffs_dict.keys(), reverse=True)]
terms = "".join(terms)
return terms[3:]

def __neg__(self):
neg_pol= self.coeffs_dict
for key in self.coeffs_dict:
neg_pol[key]= -self.coeffs_dict[key]
return Sparse_polynomial(neg_pol)

每当我尝试使用 __neg__ 方法时,原始对象就会发生变化。例如:

>>> p1= Sparse_polynomial({1:3,5:1})
>>> p1
(1*x^5) + (3*x^1)
>>> -p1
(-1*x^5) + (-3*x^1)
>>> p1
(-1*x^5) + (-3*x^1)
>>>

实在想不明白原来的p1为什么要变。我没有直接更改它,只访问了它的字段。

谁能澄清一下,以便我解决这个问题?

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