4

I have been doing some readings and thought about this code:

def change(c, n: int) -> None:
    c.x = n


class Value:
    x = 5


m = Value()
change(Value, 3)
print(m.x)
change(m, 1)
change(Value, 2)
print(m.x)

The output of this code is:

  • 3
  • 1

So what I assumed is for the 3, m & Value are aliased but changing m's attribute breaks this. I couldn't confirm this by running id() - it turned out m and value always had different ids.

Can someone explain what's going on?

Zoe
  • 27,060
  • 21
  • 118
  • 148

1 Answers1

3

When you are changing the value for Value you are changing the x value shared by all the value instances.

When you are changing the value for m, you are doing it for m and m alone, essentially overriding the class x with a new instance x. You can see it with

k = Value()
print(k.x) # 2
Guy
  • 46,488
  • 10
  • 44
  • 88