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

时间:2018-06-07 20:40:31

标签: class object variables python-2.x

我正在尝试教导需要实例变量并使用self的原因。所以我提出了以下示例。不过,它不会像我想象的那样,哈哈。我来呼吁大家回答我的问题:虽然我正在更改类变量,但是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

我的猜测是,它与我在上面的块中更改x.one的值有关,这使得x.one可能在内存中有一个新位置而不是引用example.one在记忆中的位置。

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

1 个答案:

答案 0 :(得分:1)

开始时,没有定义实例属性,只有类属性onetwo。因此,当您向实例xy询问其属性one时,他们首先检查它们是否具有实例属性,看到它们没有,然后报告类属性

     Instance    Class
x                 *1*
y                 *1*

当您分配到x.one时,此在实例one上创建了一个名为x的实例属性。因此,当您再次询问时,此时x会报告自己的实例值oney仍会报告类属性。

     Instance    Class
x      *0*         1
y                 *1*

当您更改类属性one时,这不会更改x,因为其实例属性one仍然优先于类属性。您会在y中看到差异,因为它仍然没有任何实例属性,因此会继续报告类属性。

     Instance    Class
x      *0*        -1
y                *-1*