Depth copy
One, number and string
For numbers and strings, assignments, shallow copies, and deep copies are meaningless because they always point to the same memory address.
123456789101112131415 |
import
copy
# ######### 数字、字符串 #########
n1
=
123
# n1 = "i am alex age 10"
print
(
id
(n1))
# ## 赋值 ##
n2
=
n1
print
(
id
(n2))
# ## 浅拷贝 ##
n2
=
copy.copy(n1)
print
(
id
(n2))
# ## 深拷贝 ##
n3
=
copy.deepcopy(n1)
print
(
id
(n3))
|
Second, other basic data types
For dictionaries, Ganso, and lists, the changes in the memory address of the assignment, the shallow copy, and the deep copy are different.
1. Assign Value
assignment , just create a variable that points to the original memory address, such as:
123 |
n1 = { "K1" : "WU" , "K2" : 123 , "K3" : [ "Alex" 456 ]} n2 = n1 |
2. Shallow copy
Shallow copy , creating only the first layer of data in memory
12345 |
import
copy
n1
=
{
"k1"
:
"wu"
,
"k2"
:
123
,
"k3"
: [
"alex"
,
456
]}
n3
=
copy.copy(n1)
|
3. Deep copy
deep copy , recreate all the data in memory (excluding the last layer, i.e., Python's internal optimization of strings and numbers)
12345 |
import
copy
n1
= {
"k1"
:
"wu"
,
"k2"
:
123
,
"k3"
: [
"alex"
,
456
]}
n4
= copy.deepcopy(n1)
|
"Python trail 13" Python's deep-shade copy