python copy怎么用_python何时使用copy.copy

基本上,b = a点到b点到哪里,没有别的.

你问的是可变类型.数字,字符串,元组,frozensets,布尔值,无,是不可变的.列表,字典,集合,字节数组是可变的.

如果我创建一个可变类型,如列表:

>>> a = [1, 2] # create an object in memory that points to 1 and 2, and point a at it

>>> b = a # point b to wherever a points

>>> a[0] = 2 # change the object that a points to by pointing its first item at 2

>>> a

[2, 2]

>>> b

[2, 2]

他们两个仍然指向同一个项目.

我也会评论你的原始代码:

>>>a=5 # '5' is interned, so it already exists, point a at it in memory

>>>b=a # point b to wherever a points

>>>a=6 # '6' already exists in memory, point a at it

>>>print b # b still points at 5 because you never moved it

5

你总是可以通过id(某事)看到内存中指向的东西.

>>> id(5)

77519368

>>> a = 5

>>> id(a)

77519368 # the same as what id(5) showed us, 5 is interned

>>> b = a

>>> id(b)

77519368 # same again

>>> id(6)

77519356

>>> a = 6

>>> id(a)

77519356 # same as what id(6) showed us, 6 is interned

>>> id(b)

77519368 # still pointing at 5.

>>> b

5

如果要复制结构,请使用copy.但是,它仍然不会复制interned的内容.这包括小于256的整数,True,False,None,短字符串如a.基本上,你几乎不应该使用它,除非你确定你不会被实习搞砸.

再考虑一个例子,即使使用可变类型,将一个变量指向一个新的仍然不会改变旧变量:

>>> a = [1, 2]

>>> b = a

>>> a = a[:1] # copy the list a points to, starting with item 2, and point a at it

>>> b # b still points to the original list

[1, 2]

>>> a

[1]

>>> id(b)

79367984

>>> id(a)

80533904

切片列表(无论何时使用:)都会复制.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值