1.深拷贝和浅拷贝分析
(1)浅拷贝定义:
被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。即对象的浅拷贝会对“主”对象进行拷贝,但不会复制主对象里面的对象。”里面的对象“会在原来的对象和它的副本之间共享。
简而言之,浅拷贝仅仅复制所考虑的对象,而不复制它所引用的对象
(2)深拷贝定义:
深拷贝是一个整个独立的对象拷贝,深拷贝会拷贝所有的属性,并拷贝属性指向的动态分配的内存。当对象和它所引用的对象一起拷贝时即发生深拷贝。深拷贝相比于浅拷贝速度较慢并且花销较大。
简而言之,深拷贝把要复制的对象所引用的对象都复制了一遍。
例子:
#深浅拷贝 import copy a=["one","two","three",["four","five"]] b=a.copy()#浅拷贝 c=copy.deepcopy(a)#深拷贝 print(id(a)) print(id(b)) print(id(c)) a[0]="six" print("a此时的值:",a) print("b此时的值:",b) print("c此时的值:",c) print("------------") a[3][0]="seven" print("a此时的值:",a) print("b此时的值:",b) print("c此时的值:",c)
运行结果:
1944682628416 1944682628480 1944682810432 a此时的值: ['six', 'two', 'three', ['four', 'five']] b此时的值: ['one', 'two', 'three', ['four', 'five']] c此时的值: ['one', 'two', 'three', ['four', 'five']] ------------ a此时的值: ['six', 'two', 'three', ['seven', 'five']] b此时的值: ['one', 'two', 'three', ['seven', 'five']] c此时的值: ['one', 'two', 'three', ['four', 'five']]
2.收集参数打包方式:打包成元组和打包成字典
收集参数有两种打包方式,一种是打包成元组,一个星号(*),另一种打包成字典,两个星号表示(**)
#字典打包 def test(**params): print("有%d个参数" %len(params)) print("分别是:",params) test(a=1,b=2,c="xaiogou",d=True) print("------------------") dict1={"a":1,"bb":22,"cc":"enheng","dd":True} test(**dict1)
运行结果:
有4个参数 分别是: {'a': 1, 'b': 2, 'c': 'xaiogou', 'd': True} ------------------ 有4个参数 分别是: {'a': 1, 'bb': 22, 'cc': 'enheng', 'dd': True}
3.创建不可变集合
用frozenset()函数,将set冰冻起来,即不可变
#不可变集合 set1={1,2,3,4,5,6,7} set1.add(8) print(set1) print("----------") set2=frozenset(set1) print(set2) set2.add(10)
运行结果:
{1, 2, 3, 4, 5, 6, 7, 8} ---------- frozenset({1, 2, 3, 4, 5, 6, 7, 8}) Traceback (most recent call last): File "d:PythonWorkSpace.vscode est.py", line 216, in <module> set2.add(10) AttributeError: 'frozenset' object has no attribute 'add'
可以看出,试图添加时候,报错,说明集合不可变