python 数组变量_Python类变量int vs数组

I was playing around with Python classes and arrived at the following example in which two variables which appear to be static class variables have different behavior when modified.

What's going on here? My first instinct is that something tricky is going on with references.

class Foo:

a = []

n = 0

def bar(self):

self.a.append('foo')

self.n += 1

x = Foo()

print x.a, x.n ([] 0)

x.bar()

print x.a, x.n (['foo', 1])

y = Foo()

print y.a, y.n (['foo', 0])

y.bar()

print y.a, y.n (['foo', 'foo'], 1)

解决方案

You are correct - in the case of Foo.a accessing self.a actually accesses Foo.a, which is shared between all instances of Foo. However, when you update self.n with += you actually create an instance-level variable on self that shadows Foo.n:

>>> import dis

>>> dis.dis(Foo.bar)

5 0 LOAD_FAST 0 (self)

3 LOAD_ATTR 0 (a)

6 LOAD_ATTR 1 (append)

9 LOAD_CONST 1 ('foo')

12 CALL_FUNCTION 1

15 POP_TOP

6 16 LOAD_FAST 0 (self)

19 DUP_TOP

20 LOAD_ATTR 2 (n)

23 LOAD_CONST 2 (1)

26 INPLACE_ADD

27 ROT_TWO

28 STORE_ATTR 2 (n)

31 LOAD_CONST 0 (None)

34 RETURN_VALUE

In other words, when you do self.a.append('some value') the interpreter fetches a from memory via a name on Foo and then mutates the list that Foo.a points to.

On the other hand, when you do self.n += 1 the interpreter:

Fetches n from Foo (because it can't find n on self)

Creates a new value n + 1

Stores the new value in the attribute n on self

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值