A garbage collection mechanism to explain (to know)
1. What is the garbage collection mechanism
Garbage collection (referred to as GC) is a mechanism built Python interpreter, designed to recover the value of the variable is not available memory space occupied
2. Why use garbage collection
The program is running will apply for large amounts of memory space and memory space for some useless if not cleared up it will lead to the use of depleted memory (memory overflow), causing the program to crash, so memory management is an important and complicated matter, the python interpreter that comes with garbage collection frees the programmer from the complex memory management.
3, the principle of garbage collection analysis
GC main module of Python used the "reference counting" (reference counting) to track and recover waste. On the basis of the reference count on, can also "tag - Clear" (mark and sweep) to solve the problem cycle container object may be generated by reference, and space for time by "generational recovery" (generation collection) way to further improve the efficiency of garbage collection.
3.1 What is the reference count
Value is the number of variables associated with the variable name: the reference count is
3.1.1, a direct reference to
x = 10
print(id(x))
y = x
z = x
3.1.2, an indirect reference
The main type of container for
l = ['a', 'b', x]
print(id(l[2]))
d = { 'mmm': x} # indirect reference
print(id(d['mmm'])
ps:
3.2 Clear labeling:
The original circular reference memory leaks solve problems caused by
这样栈区中不再有l1与l2,于是列表于是列表1与列表2都没有被标记为存活,二者会被清理掉,这样就解决了循环引用带来的内存泄漏问题。
3.3 分代回收
基于引用计数的回收机制,每次回收内存,都需要把所有对象的引用计数都遍历一遍,这是非常消耗时间的,于是引入了分代回收来提高回收效率,分代回收采用的是用“空间换时间”的策略。
a、分代
核心思想:gc会降低多次扫描但是没有回收的变量的扫描频率
b、回收
优点:提升效率
缺点:后一代扫描频率低于前一代,变量若回收,则会延迟
二 用户交互
1、为什么要有用户交互
用户交互就是人往计算机中input/输入数据,计算机print/输出结果,为了让计算机能够像人一样与用户沟通交流
2、如何用用户交互
本质是输入(input)输出(output)
2.1 用户输入
2.2 字符串格式化输出
2.2.1 %s(字符串型)
2.2.2 str.format:兼容性好(python2.6引进)
2.2.3 打破位置的限制,按照key=value传值
2.2.4 f''(python3.5后 #了解)
x=input('your name:')
y=input('your age:')
res=f'我的名字是{x}我的年龄是{y}'
print(res)
三 运算符
1、算术运算符
+ - *都遵循基本运算规则
/:带小数
//:只保留整数部分,不四舍五入
%:取余数
**:a ** b a的b次方
2、比较运算(结果True/False):>、>=、<、<=、==、!=(不等于)
3、赋值运算符
3.1 =:变量的赋值
3.2 增量赋值:
age=18
age=age+1 <==>age +=1
age = 19
age *=3
age /=3
age%=3
age**=3
3.3 链式赋值
x=y=z=10
id(x)=id(y)=id(z)
3.4 交叉赋值
m=10
n=20
temp=m <==> m,n=n,m
m=n
n=temp
3.5 解压赋值