gpt4 book ai didi

python - 类变量对于 list 和 int 的行为不同?

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:16 25 4
gpt4 key购买 nike

据我所知,类共享变量与类的所有实例共享。但我无法理解这个问题。

class c():
a=[1]
b=1
def __init__(self):
pass

x=c()
x.a.append(1)
x.b+=1 #or x.b=2

print x.a #[1,1]
print x.b #2

y=c()
print y.a #[1,1] :As Expected
print y.b #1 :why not 2?

y.ax.a 产生共鸣,但y.b 没有。

希望有人能解释清楚。

编辑:以及如何为整数创建相同的功能。

最佳答案

x.a.append(1)

通过调用其 append 方法更改类属性 c.a,一个 list,该方法就地修改列表。

x.b += 1

实际上是

的简写
x.b = x.b + 1

因为 Python 中的整数是不可变的,所以它们没有 __iadd__(就地添加)方法。此赋值的结果是在实例 x 上设置属性 b,值为 2(计算右侧的结果任务)。这个新的实例属性隐藏了类属性。

要了解就地操作和赋值之间的区别,请尝试

x.a += [1]

x.a = x.a + [1]

它们会有不同的行为。

编辑 通过装箱整数可以获得相同的功能:

class HasABoxedInt(object):
boxed_int = [0] # int boxed in a singleton list

a = HasABoxedInt()
a.boxed_int[0] += 1
b = HasABoxedInt()
print(b.boxed_int[0]) # prints 1, not zero

class BoxedInt(object):
def __init__(self, value):
self.value = value
def __iadd__(self, i):
self.value += i

关于python - 类变量对于 list 和 int 的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18420078/

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