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
相关文档:
例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
_ ......
源代码下载:下载地址在这里
# 023
# Tuple(元素组)是不可变的列表
tuple1 = (1, 2, 3)
print tuple1
tuple2 = (tuple1, 4, 5, 6) # 一个元素组可以作为另外一个元素组的元素
print tuple2 # 并且能够在存储的时候保持原始的逻辑关系
for ele in tuple2:
print ele
print '\n'
for ele in tuple2[0]:
pr ......
源代码下载:下载地址在这里
# 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 ......
源代码下载:下载地址在这里
# 034
class Person:
def __init__(self, name):
self.name = name # 这一句中第一个name是类中包含的域,第二个name是传进来的参数
# end of def
def sayHello(self):
print 'Hello!'
# end of def
# end of class
p = Person('Ning')
print p.nam ......
可以播放大部分的音视频.
demo download: http://www.sandy1219.com/python/media.rar
playMP3.py
# -*- coding: utf-8 -*-
import wx;
import wx.media;
import os;
import SPrint;
import mediaStateBar;
import mediaList;
import SaveLog;
import MediaItem;
woldcart = "media files|*.*|avi ......