-1

I'm learning about python class. In a toy python script,

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

I found that by running the method another_one of instance test_pass, dictionary a will be changed. However, integer b will not be altered by running the method old_one.

Why a dictionary will be changed while an integer will not?

sophros
  • 14,672
  • 11
  • 46
  • 75
meTchaikovsky
  • 7,478
  • 2
  • 15
  • 34

1 Answers1

0

Python integers are immutable, you can't change them in-place.

Take a look at the following snippet:

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

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

You can see that the first part, where the integer is being modified, the unique id() of the object changes. Afterwards x is a completely different object.

When modifying the list, its 'id()' does not change, the list is changes in-place.

The integer is immutable, they can't be magically turn into something different. Lists can.

Joe
  • 6,758
  • 2
  • 26
  • 47