简体   繁体   English

Python OOP 实例和类的可变性

[英]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 3
  • 1 1

So what I assumed is for the 3, m & Value are aliased but changing m's attribute breaks this.所以我假设的是对于 3,m 和 Value 是别名,但是更改 m 的属性会破坏这一点。 I couldn't confirm this by running id() - it turned out m and value always had different ids.我无法通过运行 id() 来确认这一点 - 结果 m 和 value 总是有不同的 ID。

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.当您更改Value的值时,您正在更改所有value实例共享的x值。

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 .当你正在改变价值m ,你这样做是为了mm孤独,基本上覆盖类x有一个新的实例x You can see it with你可以看到它

k = Value()
print(k.x) # 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM