Python类变量int vs数组 [英] Python class variable int vs array
问题描述
我在玩Python类,并得到了以下示例,其中看起来是静态类变量的两个变量在修改时具有不同的行为。
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)
推荐答案
您是正确的 - Foo.a
访问 self.a
实际访问 Foo.a
, code> Foo 。但是,当用 + =
更新 self.n
时,实际上在<$ c $上创建了一个实例级变量c> self that shadows Foo.n
:
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
换句话说,当你执行 self.a.append('some value')
解释器通过 Foo
上的名称从内存中提取 a
,然后改变 Foo.a
指向。
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.
另一方面,当你执行 self.n + = 1
解释器:
On the other hand, when you do self.n += 1
the interpreter:
- 从
n c $ c> Foo
(因为在self
上找不到n
/ li>
- 创建新值
n + 1
- 将新值存储在属性
n 在
自己
- Fetches
n
fromFoo
(because it can't findn
onself
) - Creates a new value
n + 1
- Stores the new value in the attribute
n
onself
这篇关于Python类变量int vs数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!