Var*_*rma 3 python variables reference variable-assignment
我试图了解变量如何在python中工作。说我有一个对象存储在变量中a:
>>> a = [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
如果我分配a给b,则它们都指向同一个对象:
>>> b = a
>>> b is a
True
Run Code Online (Sandbox Code Playgroud)
但是,如果我重新分配a或b,那就不再正确了:
>>> a = {'x': 'y'}
>>> a is b
False
Run Code Online (Sandbox Code Playgroud)
这两个变量现在具有不同的值:
>>> a
{'x': 'y'}
>>> b
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我不明白为什么变量现在不同。为什么a is b不再是真的?有人可以解释发生了什么吗?
Mis*_*agi 10
Python具有引用对象的名称。对象与名称分开存在,名称与它们引用的对象分开存在。
# name a
a = 1337
# object 1337
Run Code Online (Sandbox Code Playgroud)
当为“名称分配名称”时,右侧评估所引用的对象。类似于如何2 + 2评估4,a评估原始1337。
# name b
b = a
# object referred to by a -> 1337
Run Code Online (Sandbox Code Playgroud)
At this point, we have a -> 1337 and b -> 1337 - note that neither name knows the other! If we test a is b, both names are evaluated to the same object which is obviously equal.
Reassigning a name only changes what that name refers to - there is no connection by which other names could be changed as well.
# name a - reassign
a = 9001
# object 9001
Run Code Online (Sandbox Code Playgroud)
At this point, we have a -> 9001 and b -> 1337. If we now test a is b, both names are evaluated to different objects which are not the same.
If you come from languages such as C, then you are used to variables containing values. For example, char a = 12 can be read as "a is a memory region containing 12". On top, you can have several variables use the same memory. Assigning another value to a variable changes the content of the shared memory - and therefore the value of both variables.
+- char a -+
| 12 |
+--char b -+
# a = -128
+- char a -+
| -128 |
+--char b -+
Run Code Online (Sandbox Code Playgroud)
This is not how Python works: names do not contain anything, but refer to separate values. For example, a = 12 can be read as "a is a name which refers to the value 12". On top, you can have several names refer to the same value - but it will still be separate names, each with its own reference. Assigning another value to a name changes the reference of that name - but leaves the reference of the other name untouched.
+- name a -+ -\
\
--> +- <12> ---+
/ | 12 |
+- name b -+ -/ +----------+
# a = -128
+- <-128> -+
+- name a -+ -----> | -128 |
+----------+
+- <12> ---+
+- name b -+ -----> | 12 |
+----------+
Run Code Online (Sandbox Code Playgroud)