易截截图软件、单文件、免安装、纯绿色、仅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个例子 之 24

# 027
toolName = 'Google'
if toolName.startswith('Go'):
print 'The tool\'s name starts with \"Go\".'
if 'oo' in toolName:
print 'The tool\'s name contains the stirng "oo".'
print toolName.find('gl') # 返回首次出现“gl”字符串的索引
if toolName.find('Baidu ......

Python入门的36个例子 之 31

源代码下载:下载地址在这里
# 035
class Person:
population = 0 #这个变量是属于整个类的
def __init__(self, name):
self.name = name
print '初始化 %s' % self.name
Person.population += 1
# end of def
def __del__(self):
print '%s says bye.' % self. ......

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个例子 之 36

# 040
import time
try:
f = file('040_Finally.py')
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(0.33)
print line,
# end of while
finally:
f.close()
print 'Closed the file.'
# end of try
output:
> ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号