简体   繁体   中英

How does python memory management work with variables?

Suppose i have a var like this.

num1 = 1   

now If I do

num3 = num1

If I am correct this num3 is referencing to the value of num1 like pointer in C because when I do

print(num1 is num3)

It returns true because both are pointing at a same object or value in memory

But now if I change my value like this

num3 = 3

And then I print

print(num1,num3) 

It returns "1,3"

Why hasn't the num1 value changed if I changed the second variable value which is pointing to the same object or value

I use mermaid to draw several sketches. Hope they are helpful to you:

Int Assignment

整数分配

A is B is equivalent to id(A) == id(B) , the id of the variable that points to the same memory (rectangle in the sketch) is the same.

List Assignment

As mentioned in the comments, the assignment is the same regardless of the type.

列表分配

What you should be careful

Objects which is referenced by multiple objects changing are what we need to worry about.

你应该注意什么

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM