类变量对于 list 和 int 的行为不同吗? [英] Class variables behave differently for list and int?

查看:45
本文介绍了类变量对于 list 和 int 的行为不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,类共享变量与类的所有实例共享.但我很难理解这一点.

The class shared variables are shared with all the instances of the classes as far as I know. But I am having trouble getting my head around this.

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 没有.

y.a resonates with the x.a but y.b doesn't.

希望有人能澄清一下.

如何为整数创建相同的功能.

And how can the same functionality be created for ints.

推荐答案

x.a.append(1)

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

changes the class attribute c.a, a list, by calling its append method, which modifies the list in-place.

x.b += 1

实际上是

x.b = x.b + 1

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

because integers in Python are immutable, so they don't have an __iadd__ (in-place add) method. The result of this assignment is to set an attribute b on the instance x, with value 2 (the result of evaluating the right-hand side of the assignment). This new instance attribute shadows the class attribute.

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

To see the difference between an in-place operation and an assignment, try

x.a += [1]

x.a = x.a + [1]

这些会有不同的行为.

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

EDIT The same functionality can be obtained for integers by boxing them:

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

这篇关于类变量对于 list 和 int 的行为不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆