当前位置:编程学习 > python >>

Python 初体验之 对象的引用和拷贝

写过Java的都知道,这个对象的引用和对象的clone是完全不用的一回事,作为面向对象的语言,Python也不例
 
外,他的大部分声明或者使用一个变量都是对于对象的引用,但是偶尔情况下面我们也会不得不使用对象的clone,下
 
面我们来一个例子说明一下这个对象的clone和对象的引用的区别,这个很重要。
 
首先看一下代码
 
 
[python] 
''''' 
Created on 2013-1-25 
 
@author: Administrator 
'''  
shoplist = ['Apple','mango','carrot','banana']  
mylist = shoplist  
  
del shoplist[0]  
  
print("shoplist is",shoplist)  
print("mylist is",mylist)  
  
#下面使用拷贝   
mylist = shoplist[:]  
del shoplist[0]  
print("shoplist is",shoplist)  
print("mylist is",mylist)  
 
'''
Created on 2013-1-25
 
@author: Administrator
'''
shoplist = ['Apple','mango','carrot','banana']
mylist = shoplist
 
del shoplist[0]
 
print("shoplist is",shoplist)
print("mylist is",mylist)
 
#下面使用拷贝
mylist = shoplist[:]
del shoplist[0]
print("shoplist is",shoplist)
print("mylist is",mylist)
 
 
输出的结果为
 
 
[python]  
shoplist is ['mango', 'carrot', 'banana']  
mylist is ['mango', 'carrot', 'banana']  
shoplist is ['carrot', 'banana']  
mylist is ['mango', 'carrot', 'banana']  
 
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
shoplist is ['carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
 
大家可以很清楚的看出来,这个序列的引用和对象的clone是什么个概念,主要是需要熟悉一下这个序列的clone。,
 
就是使用shoplist[:],不一定常用,但是mark一下
 
补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,