深浅拷贝区别
深拷贝
- 新对象地址改变
- 新对象的元素地址改变(其中只有可变类型地址改变)
- 新对象只有第一层的可变类型元素地址改变 第二层开始保持原有对象地址
obj = [] import copy obj1 = copy.deepcopy(obj)
浅拷贝
- 新对象地址改变 元素地址不变
- 新对象的第一层可变对象元素变化 会影响新对象
obj1 = obj.copy()
深浅拷贝的区别
- 深浅拷贝对于可变对象地址的区别
import copy stuff = [[1, 2], {1, 2}, {1: 'a', 2: 'b'}, (1, 2), 'abc', 123] stuff_deep = copy.deepcopy(stuff) stuff_shallow = stuff.copy() i = 0 while i < len(stuff): print(type(stuff[i]), id(stuff[i]), '\t', stuff[i], 'origin') print(type(stuff_deep[i]), id(stuff_deep[i]), '\t', stuff_deep[i], 'deep') print(type(stuff_shallow[i]), id(stuff_shallow[i]), '\t', stuff_shallow[i], 'swallow') print() i += 1# 其中浅拷贝第一层对象地址不改变 深拷贝的可变对象地址发生改变 <class 'list'> 1274468741512 [1, 2] origin <class 'list'> 1274468741768 [1, 2] deep <class 'list'> 1274468741512 [1, 2] swallow <class 'set'> 1274468719080 {1, 2} origin <class 'set'> 1274468810824 {1, 2} deep <class 'set'> 1274468719080 {1, 2} swallow <class 'dict'> 1274466093240 {1: 'a', 2: 'b'} origin <class 'dict'> 1274466438984 {1: 'a', 2: 'b'} deep <class 'dict'> 1274466093240 {1: 'a', 2: 'b'} swallow <class 'tuple'> 1274468742216 (1, 2) origin <class 'tuple'> 1274468742216 (1, 2) deep <class 'tuple'> 1274468742216 (1, 2) swallow <class 'str'> 1274466032112 abc origin <class 'str'> 1274466032112 abc deep <class 'str'> 1274466032112 abc swallow <class 'int'> 140735165477072 123 origin <class 'int'> 140735165477072 123 deep <class 'int'> 140735165477072 123 swallow
深拷贝中 第一层的可变类型地址会改变list set dic
直接赋值
- 地址分享
obj1 = obj
方法参数
- 默认参数
def fun(a=10): return a pass print(fun()) # 10- 方法内的可变参数可不传参
- 可变参数要在形参的最右端(不能在非默认参数的右边)
- 关键参数
- 指调用函数时的传递方式
print(fun(a=9)) - 可变长度参数
- 分为两种 *为元组类型 **为字典类型
- 非要求参数 调用时可不传递任何参数
def fun1(*args, **kwargs): print(type(args)) # <class 'tuple'> print(type(kwargs)) # <class 'dict'> pass fun1() - 传递参数时的序列解包
- 当调用方法需要多个参数时 可使用可迭代对象进行传递 使用*可迭代对象
def fun2(a, b, c): print(a + b + c) pass li = [1, 2, 3] fun2(*li)
版权声明:本文为quntinli原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。