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:
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With