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

标签 python class oop

<分区>

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

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为什么要变。我没有直接更改它,只访问了它的字段。

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

最佳答案

I made no direct changes to it, only accessed it's field.

那不是真的:看看你的代码......

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

您获取了对系数字典的引用并否定了每个成员。这不是副本;这是对原文的引用。

如果您尝试返回单独的字典,请使用多种可用的复制方法之一。一个流行的方法是从类本身复制:

neg_pol = self.coeffs_dict.copy()

要检查项目的“句柄”,请使用 id 方法。例如:

print id(self.coeffs_dict), id(neg_pol)

这很容易表明这两个变量名称指的是同一个对象。

关于python - 为什么我的实例会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44447495/

相关文章:

ios - [nav visibleViewController] 的类混合

python - 在 Python 中是否可以声明必须重写该方法?

python - 使用 anaconda2 安装 python caffe (pycaffe)

python - Bokeh 服务器的入口点

java - 扩展某个类的通用映射到类

C++ 在一个类中实例化一个类。正确的方法?

oop - 两个默认方法互相调用

objective-c - Objective-C - 如何实现自定义回调方法但强制执行特定参数?

python - 在 python 中捆绑变量的正确方法是什么

python - 自然排序 Pandas DataFrame