深、浅拷贝 | 方法参数

深浅拷贝区别

深拷贝

  • 新对象地址改变
  • 新对象的元素地址改变(其中只有可变类型地址改变)
  • 新对象只有第一层的可变类型元素地址改变 第二层开始保持原有对象地址
    	obj = []
    	import copy
    	obj1 = copy.deepcopy(obj)
    

浅拷贝

  • 新对象地址改变 元素地址不变
  • 新对象的第一层可变对象元素变化 会影响新对象
    obj1 = obj.copy()
    

深浅拷贝的区别

  1. 深浅拷贝对于可变对象地址的区别
    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
    

方法参数

  1. 默认参数
    def fun(a=10):
    	return a
    	pass
    print(fun())  # 10
    
    • 方法内的可变参数可不传参
    • 可变参数要在形参的最右端(不能在非默认参数的右边)
  2. 关键参数
    • 指调用函数时的传递方式
     	print(fun(a=9))
    
  3. 可变长度参数
    • 分为两种 *为元组类型 **为字典类型
    • 非要求参数 调用时可不传递任何参数
    def fun1(*args, **kwargs):
    	print(type(args))  # <class 'tuple'>
    	print(type(kwargs))  #  <class 'dict'>
    	pass
    
    fun1()
    
  4. 传递参数时的序列解包
    • 当调用方法需要多个参数时 可使用可迭代对象进行传递 使用*可迭代对象
    def fun2(a, b, c):
    print(a + b + c)
    pass
    
    li = [1, 2, 3]
    fun2(*li)
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值