Python: 对象与参考

来源:互联网 发布:高二数学算法初步 编辑:程序博客网 时间:2024/04/29 09:42

Python: 对象与参考

标签: python 对象 参考

by 小威威


1.对象与参考

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

我的理解就是:我们所定义的变量名,其实就是一个对象,我们给这个对象所赋的值即为这个对象的参考,他不能代表变量本身。所以在给变量赋值时要注意:
(1) 如果你只是想将列表复制到另一个变量中,此时就要用到切片操作符,即:

list2 = list1[:]

此时无论你对list2如何操作,都对list1没有影响。
(2)如果你想通过多个对象来控制列表,此时就无需用到切片操作符,直接赋值即可,即:

list2 = list1

此时,list1存储的列表受到了list1与list2两个对象的控制,即这两个对象所指向的内容是同一个(类似于C语言中的指针,list1与list2指向同一块内存)。对list2的操作就对list1有影响,同样的,对list1操作同样也会对list2造成影响。

2.实例

#!/usr/bin/python3# Filename:reference.pyprint ('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 objectprint ('Copy by making a full slice')# make a copy by doing a full slicemylist = shoplist[:] # make a copy by doing a full slicedel shoplist[0]# remove first itemprint ('shoplist is', shoplist)print ('mylist is', mylist)# notice that now the two lists are different

输出结果如下:

appledeMacBook-Pro-2:Desktop apple$ python3 reference.pySimple Assignmentshoplist is ['mango', 'carrot', 'banana']mylist is ['mango', 'carrot', 'banana']Copy by making a full sliceshoplist is ['carrot', 'banana']mylist is ['mango', 'carrot', 'banana']

以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨。


0 0