易截截图软件、单文件、免安装、纯绿色、仅160KB

Python模块学习

  copy模块用于对象的拷贝操作。该模块非常简单,只提供了两个主要的方法:
copy.copy

copy.deepcopy
,分别表示浅复制与深复制。什么是浅复制,什么是深复制,网上有一卡车一卡车的资料,这里不作详细介绍。复制操作只对复合对象有效。用简单的例子来分别介绍这两个方法。
浅复制只复制对象本身,没有复制该对象所引用的对象。
#coding=gbk
import copy
l1 = [1, 2, [3, 4]]
l2 = copy.copy(l1)
print l1
print l2
l2[2][0] = 50
print l1
print l2
#---- 结果 ----
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [50, 4]]
[1, 2, [50, 4]]
同样的代码,使用深复制,结果就不一样:
import copy
l1 = [1, 2, [3, 4]]
l2 = copy.deepcopy(l1)
print l1
print l2
l2[2][0] = 50
print l1
print l2
#---- 结果 ----
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [50, 4]]

改变copy的默认行为
  在定义类的时候,通过定义__copy__和__deepcopy__方法,可以改变copy的默认行为。下面是一个简单的例子:
class CopyObj(object):
def __repr__(self):
return "CopyObj"

def __copy__(self):
return "Hello"
obj = CopyObj()
obj1 = copy.copy(obj)
print obj
print obj1
#---- 结果 ----
CopyObj
Hello


相关文档:

Python入门的36个例子 之 18

例1:
# _018
# This is a module (if write Chinese in a module, there will be a error)
def func1():
print 'This is function 1.'
def func2():
print 'This is function 2.'
def func3():
print 'This is function 3.'
# 019
# 使用“import”语句调用模块:
import _018_Module
_ ......

Python入门的36个例子 之 25

源代码下载:下载地址在这里
# 028
consoleInput = raw_input('请输入点什么吧:')
aFile = file(r'C:\out.txt', 'w')
aFile.write(consoleInput + '\n')
aFile.write('这里是第二行')
aFile.close()

output:
>>>
请输入点什么吧:haha
>>>
......

Python入门的36个例子 之 26

源代码下载:下载地址在这里
# 029
aFile = file(r'C:\in.txt', 'r')
while True:
line = aFile.readline()
if len(line) == 0:
break
# end of if
print line,
# end of while
aFile.close()

output:
>>>
This is the first line.
This is the second line.
This is ......

Python入门的36个例子 之 32

源代码下载:下载地址在这里
A Byte Of Python
中关于继承有这样的文字:
Suppose you want to write a program which has to keep track of the
teachers and students in a college. They have some common
characteristics such as name, age and address. They also have specific
characteristics such as sala ......

Python入门的36个例子 之 33

源代码下载:下载地址在这里
# 037
fileName = ''
while 1:
fileName = raw_input("Input a file name:")
if fileName == 'q':
break
try:
f = file(fileName, 'r')
print 'Opened a file.'
except:
print 'There is no file named', fileName
......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号