Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

python 类 属性类型为字典时候 值有问题

代码如下

class Point:
    dic = {}

    def __init__(self, x=0):
        self.dic[x] = x


pt1 = Point(1)
print(pt1.dic)
pt2 = Point(2)
print(pt2.dic)

他的打印结果是

{1: 1}
{1: 1, 2: 2}

这里pt2对象为何受到了pt1对象的影响?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这时 Python 类变量的特性:类及其所有实例共享类变量。

你的两个实例 pt1 和 pt2 访问的 dic 都是同一个 dic。在实际使用中,应该避免这样做,尤其该变量为 可变对象 时(如 list、dict)。

针对你的场景,你完全可以这样做:

class Point:

    def __init__(self, x=0):
        self.dic = {x: x}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...