【发布时间】:2018-09-01 22:08:46
【问题描述】:
我是这门语言的新手,对 Python 中的引用有点困惑。
考虑这段代码:
class A:
def __init__(self, x):
self.x = x
a = A(3)
v=[a]
print(f'obj before: v[0].x={v[0].x}')
a.x = a.x + 1
print(f'obj after: v[0].x={v[0].x}')
b = 3
w=[b]
print(f'int before: w[0]={w[0]}')
b = b + 1
print(f'int after: w[0]={w[0]}')
====================== 输出:
obj before: v[0].x=3
obj after: v[0].x=4
int before: w[0]=3
int after: w[0]=3
为什么 obj 和 int 版本的代码工作方式不同?
【问题讨论】: