Iは、辞書によって表される多項式オブジェクトのクラス、作っている:インスタンスが変わるのはなぜですか?
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
。私はそれに直接的な変更を加えず、フィールドにアクセスしました。
私はこれを解決できるように誰でも明記できますか?
new_dict = dictの(old_dict)あなたはコピーを – Rosh