Python 3.x变量赋值与绑定的区别及绑定语法咨询
Great question! Let's break this down clearly—Python's variable model works a bit differently than some other languages, so it's totally normal to have this confusion.
为什么你的代码里var2 = var1没让两个变量“绑定”?
First, let's get one key concept straight: in Python, variables are just labels that point to objects in memory, not boxes that hold values.
Let's walk through your code line by line:
var1 = 1 # Creates an integer object `1`, then sticks the label `var1` on it var2 = var1 # Now `var2` is another label stuck to the EXACT SAME `1` object var2 = var2 + 3 # Here's the critical part: integers are immutable. `var2 +3` creates a NEW integer object `4`, then moves the `var2` label to this new object. `var1` still stays attached to the original `1`.
That's why your print statements output 1 and 4—the two variables are now pointing to entirely separate objects.
怎么让两个变量绑定到同一内存空间(并保持关联)?
This only works with mutable objects (like lists, dictionaries, sets, or custom classes you define). Mutable objects can be modified in-place without creating a brand new object, so all labels pointing to it will see the changes.
Here's an example:
var1 = [1] # Creates a mutable list object `[1]`, labels it `var1` var2 = var1 # `var2` also gets stuck to the same list object var2.append(3) # Modifies the list IN-PLACE—no new object is made print(var1) # Outputs [1, 3] (since it's the same list) print(var2) # Outputs [1, 3]
Now both variables are "bound" to the same memory space because they reference the same mutable object. Any in-place changes to that object will show up in both variables.
For immutable objects (int, str, tuple, etc.), this kind of binding isn't possible. Any operation that looks like a "modification" actually creates a new object, so reassigning the variable just moves its label to the new object, leaving the original variable pointing to the old one.
如何避免意外绑定两个变量?
If you're working with mutable objects and don't want changes to one variable affecting the other, you need to create a copy of the object instead of just reassigning the label.
Some common ways to make copies:
- For lists:
var2 = var1.copy()orvar2 = var1[:] - For dictionaries:
var2 = var1.copy() - For nested or complex objects: use the
copymodule'scopy.deepcopy()function
This way, var2 points to a brand new, separate object in memory—modifying it won't have any impact on var1.
内容的提问来源于stack exchange,提问作者James Bell

