为什么字典会被类实例更改,而整数却不会

时间:2018-12-03 12:15:03

标签: python dictionary

我正在学习python类。在玩具python脚本中,

class test():
    def __init__(self, a, b):
        self.new = a
        self.old = b

    def another_one(self):
        temp = self.new
        for key in temp.keys():
            temp[key] += 1

    def old_one(self):
        old = self.old
        old += 1

a = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5}
b = 5
test_pass = test(a, b)
test_pass.another_one(), test_pass.old_one()
a, b

我发现通过运行实例another_one的方法test_pass,字典a将被更改。但是,将不会通过运行方法b来更改整数old_one

为什么字典会被更改而整数不会被更改?

1 个答案:

答案 0 :(得分:0)

Python整数是不可变的,您不能就地更改它们

看看下面的代码片段:

x = 2
print(id(x))
x += 1
print(id(x))

x = [2]
print(id(x))
x += [1]
print(id(x))

您会看到对象的唯一部分id()发生变化,其中第一部分正在修改整数。之后x是一个完全不同的对象。

修改列表时,它的'id()'不变,列表是就地更改

整数是不可变的,它们不能神奇地变成不同的东西。列表可以。