【发布时间】:2018-06-07 20:40:30
【问题描述】:
我正在尝试说明需要实例变量的原因并使用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 在内存中的位置。
如果您能给我一个更详细的原因,我将非常感激,并能够将知识传授给我的学生。
【问题讨论】:
标签: class object variables python-2.x