Python一天入门12:数据结构-参考

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定

一般说来,你不需要担心这个,只是在参考上有些细微的效果需要你注意。这会通过下面这个例子加以说明。

对象与参考:

#!/usr/bin/python

# 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]

 

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

 

输出:

执行: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']

 

说明:

大多数解释已经在程序的注释中了。你需要记住的只是如果你想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值