Python入门系列:References

[size=large][b]References[/b][/size]
当你创建对象并把它赋给一个变量后,这个变量仅仅只是关联到(refer to)这个对象,而并不代表这个对象本身。这就意味着变量名指向了你的计算机的内存中对象保存的位置。这个叫做把变量名绑定到对象上(This is called as binding of the name to the object)。
通常你并不需要太关注这个问题,但却会对你的应用有微妙的影响,所以你需要意识到这个问题。
请看下面的示例:
# Filename: reference.py
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same
object!
del shoplist[0] # I purchased the first item, so I remove it from the
list
print('shoplist is', shoplist)
print('mylist is', mylist)
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print('Copy by making a full slice')
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print('shoplist is', shoplist)
print('mylist is', mylist)
# notice that now the two lists are different

[size=medium]输出结果:[/size]
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

执行过程:
程序的注释部分已经说的很明白,值得注意的是如果你想对一个list或者类似的sequence对象或其他的复杂做复制操作的话(像integer这样的简单对象不需要考虑这个问题),你就要使用slicing操作来完成复制。如果仅仅把一个变量名赋值给另外一个变量名,那么这两个变量将指向同一个对象。如果你没有注意到这一点,那么将会给你带来不必要的麻烦。

说明:该文章从 A byte of Python v1.92 for Python3.0翻译而来,望指正
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值