gpt4 book ai didi

python - 为什么列表是共享的而不是 python 中的变量(类级别)

转载 作者:行者123 更新时间:2023-11-28 20:45:33 24 4
gpt4 key购买 nike

<分区>

class abc :
x = 10
list = []
def __init__(self):
self.a = 30
self.b = 40

a = abc()
b = abc()
a.x = a.x + 1
print a.x
print b.x
a.list.append(1)
print b.list

Output :
10
11
[1]

所以我们看到 x 没有在对象 ab 之间共享,但是 list 是共享的。有人可以解释这种行为吗?

所以它的答案似乎在于列表是可变对象而数字不是:

class abc :
x = 10
m_list = []

def __init__(self):
self.a = 30
self.b = 40



a = abc()
b = abc()
print id(a.x)
a.x = a.x + 1
print id(a.x)
print a.x
print b.x
print id(a.m_list)
a.m_list.append(1)
print id(a.m_list)
print b.m_list
print id(b.m_list)


output :
5342052
5342040
11
10
38600656
38600656
[1]
38600656

but this is so strange ...numbers are immutable ?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com