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

标签 python oop

<分区>

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 ?

最佳答案

它们都在该类的所有实例中共享,但区别在于列表是可变的,而整数是不可变的

这个:

a.x = a.x + 1

创建一个新的不可变 int 对象* 然后将 a.x(但不是 b.x)指向新对象.

相比之下,这个:

a.list.append(1)

修改可变 list 对象 a.list(和 b.list)已经指向原地。

您可以使用例如更一致地修改不可变类属性

abc.x = abc.x + 1
abc.list.append(1)

并且不要调用您自己的变量 list!

* 小整数在 CPython 中是“驻留的”,但我们暂时不用担心这个

关于python - 为什么列表是共享的而不是 python 中的变量(类级别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23137283/

相关文章:

python - 'Manager' 对象在 django 1.7 中没有属性 'create_user'

python - 使用 Python 进行 GPG 解密(作为 Windows 服务)

javascript - 如何将 $(this) 对象从一个函数传递到另一个函数?

c - 即使具有显式可见性,C 共享库中的某些 C 符号也不会导出

c++ - 是否可以在成员例程中使用 const_cast 来避免重复代码

Python列表拆分

生成器理解中的 Python StopIteration

python - 与卷积的中心差异

oop - 为什么协议(protocol)的关联类型在 Swift 中不使用泛型类型语法?

javascript - 为什么即使对象生成随机健康状况,所有实例都具有相同的健康状况