Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python OOP instances & classes mutability

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?

like image 821
Michael Sheinman Avatar asked Sep 02 '25 09:09

Michael Sheinman


1 Answers

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
like image 167
Guy Avatar answered Sep 05 '25 00:09

Guy