1、内存管理相关知识
1、变量无须事先声明,也不需要指定类型,这是Python作为动态语言的特性
2、Python编程中,一般无须关心变量的存亡,一般也不用关心内存的管理
3、Python使用引用计数记录所有对象的引用数
3.1 当对象引用数变为0,它就可以被垃圾回收 GC
3.2 计数增加
3.2.1 赋值给其它变量就增加引用计数
3.2.2 实参传参
3.3 计数减少
3.3.1 函数运行结束时,局部变量就会自动销毁,对象引用计数减少
3.3.2 变量被赋值给其它对象
4、有关性能的时候,就需要考虑变量引用问题,但是该释放内存还是尽量不释放,需要看具体需求
2、示例
import sys
x = []
print(1, 'count(x) =', sys.getrefcount(x))
y = x
print(2, 'count(x) =', sys.getrefcount(x), 'count(y) =', sys.getrefcount(y))
x = 5
print(3, 'count(x) =', sys.getrefcount(x), 'count(y) =', sys.getrefcount(y))
z= 5
print(4, 'count(x) =', sys.getrefcount(x), 'count(y) =', sys.getrefcount(y), 'count(z) =', sys.getrefcount(z))
1 count(x) = 2
2 count(x) = 3 count(y) = 3
3 count(x) = 632 count(y) = 2
4 count(x) = 633 count(y) = 2 count(z) = 633