代码之家  ›  专栏  ›  技术社区  ›  natn2323

更改类变量不影响对象的值

  •  0
  • natn2323  · 技术社区  · 8 年前

    我试图解释需要实例变量的原因,并使用 self . 所以我想出了下面的例子。不过,这不是我想的那样,哈哈。我是来呼吁大家回答我的问题的:虽然我正在更改类变量,但是最后一个print语句是如何 x.one 没有打印出来 -1 也?

    class example():
      one = 1
      two = 2
    
    # Creating 2 'example' objects, x and y
    x = example()
    y = example()
    print("x is: ", x.one, "y is: ", y.one) # output: x is 1, y is 1
    
    # From the print statement, we'll see that changing one class object does not affect another class object
    x.one = 0
    print("x is: ", x.one, "y is: ", y.one) # output: x is 0, y is 1
    
    # But what if we changed the class itself?
    example.one = -1
    print("x is: ", x.one, "y is: ", y.one) # output: x is 0, y is -1
    

    我猜这和我改变 小精灵 的值,它使 小精灵 可能在内存中有一个新位置而不是引用 example.one 在内存中的位置。

    如果你能给我一个更详细的理由,我将非常感谢,并将知识传授给我的学生。

    1 回复  |  直到 8 年前
        1
  •  1
  •   glibdud    8 年前

    开始时,没有定义实例属性,只有类属性 one two . 所以当你问这些例子 x y 因为他们的特性 ,它们首先检查是否有实例属性,查看是否有,然后报告类属性。

         Instance    Class
    x                 *1*
    y                 *1*
    

    当你分配到 x.one ,这个 创建 一个名为 例如 X . 所以当你再问他们的时候,这次 X 报告自己的实例值 Y 仍然报告类属性。

         Instance    Class
    x      *0*         1
    y                 *1*
    

    然后更改类属性时 ,这是不变的 X 因为它的实例属性 仍然优先于类属性。你看到了 Y ,因为它仍然没有任何实例属性,因此继续报告类属性。

         Instance    Class
    x      *0*        -1
    y                *-1*
    
    推荐文章