<分区>
我正在制作一类由字典表示的多项式对象:
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
为什么要变。我没有直接更改它,只访问了它的字段。
谁能澄清一下,以便我解决这个问题?