Identity (id), type (type), value

# 知识点1.所有Python对象都拥有三个属性:身份(id)、类型(type)、值。

import copy
a=[1,2,[3,4]]
b=a
a.append(5)
print(a,' adress: ',id(a))  # [1, 2, [3, 4], 5]  adress:  2670537167752
print(b,' adress: ',id(b))  ## [1, 2, [3, 4], 5]  adress:  2670537167752


c=copy.copy(a)
print(a,' adress: ',id(a))  # [1, 2, [3, 4], 5]  adress:  2670537167752
print(c,' adress: ',id(c))  # [1, 2, [3, 4], 5]  adress:  2670566859528

a.append(6)
print(a,' adress: ',id(a))  # [1, 2, [3, 4], 5, 6]  adress:  2670537167752
print(c,' adress: ',id(c))  # [1, 2, [3, 4], 5]  adress:  2670566859528

a[2].append(4)  #二者子对象变化一致
print(a,' adress: ',id(a))  # [1, 2, [3, 4, 4], 5, 6]  adress:  2670537167752
print(c,' adress: ',id(c))  # [1, 2, [3, 4, 4], 5]  adress:  2670566859528


d=copy.deepcopy(a)
print(a,' adress: ',id(a))  # [1, 2, [3, 4, 4], 5, 6]  adress:  2670537167752
print(d,' adress: ',id(d))  # [1, 2, [3, 4, 4], 5, 6]  adress:  2670567475592

a.append(7)
print(a,' adress: ',id(a))  # [1, 2, [3, 4, 4], 5, 6, 7]  adress:  2670537167752
print(d,' adress: ',id(d))  # [1, 2, [3, 4, 4], 5, 6]  adress:  2670567475592

a[2].append(4)
print(a,' adress: ',id(a))  # [1, 2, [3, 4, 4, 4], 5, 6, 7]  adress:  2670537167752
print(d,' adress: ',id(d))  # [1, 2, [3, 4, 4], 5, 6]  adress:  2670567475592

Knowledge point 2: mutable and immutable objects

Variable objects: lists, dictionaries, collections. The so-called variable means that the value of the variable object is variable, and the identity is unchanged.
Immutable objects: numbers, strings, tuples. An immutable object means that the identity and value of the object are immutable.

Knowledge point 3: Reference

In a Python program, each object will apply for a space in the memory to store the object, and the address of the object in the memory is called a reference. When developing a program, the defined variable name is actually referenced by the address of the object.

Guess you like

Origin blog.csdn.net/weixin_42322206/article/details/113913447