reference

  1. 创建一个对象并给它赋一个变量的时候,这个变量仅仅 引用 那个对象,而不是表示这个对象本身
  2. 如果想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么你必须使用切片操作符来取得拷贝。如果你只是想要使用另一个变量名,两个名称都 引用 同一个对象,那么如果你不小心的话,可能会引来各种麻烦。
# !D:\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', 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', shoplist
print 'mylist', mylist
# notice that now the two list are different

结果:
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist ['mango', 'carrot', 'banana']
mylist ['carrot', 'banana']

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容