摘要:6.3限制属性的设置通常情况下,Python允许随意给类和类实例增加属性。但是对于某些特性的类,希望这种自由受到限制一种优雅的实现方法是写一个类和一个简单的自定义元类,再加上一个封装函数。# -*- coding: cp936 -*-def no_new_attributes(wrapped_setattr): """试图添加新属性,报错 但是允许已经存在的属性被随意设置""" def __setattr__(self,name,value): if hasattr(self,name): wrapped_setattr(self,.
阅读全文
摘要:6.2 定义常量常量是指一旦初始化后就不能修改的固定值。c++中使用const保留字指定常量,而python并没有定义常量的保留字。但是python是一门功能强大的语言,可以自己定义一个常量类来实现常量的功能。# -*- coding: UTF-8 -*-# Filename: const.py# 定义一个常量类实现常量的功能## 该类定义了一个方法__setattr()__, 和一个异常ConstError, ConstError类继承# 自类TypeError. 通过调用类自带的字典__dict__, 判断定义的常量是否包含在字典# 中。如果字典中包含此变量,将抛出异常,否则,给新创建的常
阅读全文
摘要:6.1 温标的转换在开式温度,摄氏度,华氏温度及兰金温度之间做转换将功能封装在如下的类中:# -*- coding: cp936 -*-class Temperature(object): coefficients = {'c':(1.0,0.0,-273.15),'f':(1.8,-273.15,32),'r':(1.8,0.0,0.0)} def __init__ (self,**kwargs): try: name,value = kwargs.popitem() except KeyError: nam...
阅读全文
摘要:4.8二维阵列变换讲一个列表的列表,将行换成列,列换成行。可以使用列表推导式>>> arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]>>> newarr= [[row[col] for row in arr] for col in range(len(arr[0]))]>>> print newarr[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]还有一种方法,使用内建函数zip>>> print map(list,zip(*arr))[[1,
阅读全文
摘要:4.6展开一个嵌套的序列使用了递归生成器,生成器(yield)这个东东的左右是每次产生多个值,函数就被冻结,函数停在那点等待激活,被激活后就从停止的那点开始执行生成器这个东东感觉是只可意会不可言传呀。def list_or_tuple(x): return isinstance(x, (list, tuple))def flatten(sequence, to_expand=list_or_tuple): for item in sequence: if to_expand(item): for subitem in flatten(item, to...
阅读全文
摘要:4.1 对象拷贝和C++一样,python也有深拷贝和浅拷贝前拷贝,如下,虽然生成了一个新的对象,但是对象内部属性和内容依然引用原对象>>> list_of_lists = [['a'],[1,2],['z',23]]>>> copy_lol= copy.copy(list_of_lists)>>> copy_lol[1].append('boo')>>> print list_of_lists,copy_lol[['a'], [1, 2, 'boo&
阅读全文
摘要:3.10 反复执行某个命令使用time.sleep方法,以60秒为周期,通过os.system方法来执行命令。sys.argv[0]获取的第一个参数是脚本名称,之后是参数,当参数小于1或者大于2说明参数的个数不对。当参数个数为1时,执行第一种情况,周期默认为60秒,当参数个数为2时,执行第二种情况,时间周期通过脚本自己设定参数import time, os, sysdef main(cmd, inc=60): while True: os.system(cmd) time.sleep(inc)if __name__ == '__main__' : num...
阅读全文
摘要:3.5 计算日期之间的工作日文中使用了dateutil模块,由于deteutil模块属于第三方模块,需要额外安装,所以尝试不适用此模块来实现此功能方法就是使用weekday()方法,由于周六与周日的数值为5和6,不属于这两天的即是工作日:>>> import datetime>>> def workday_between(startday,endday): oneday = datetime.timedelta(days=1) daycheck = endday workday_num = 0 while daycheck != startday: if .
阅读全文
摘要:3.3 计算日期之间的时段给定两个日期,需要计算两个日期之间隔了几周感觉没有必要使用文中提到的dateutil模块,自己写了一段:>>> def totaltimer(times): td = datetime.timedelta(0) duration = sum([datetime.timedelta(minutes=x,seconds=y) for x,y in times],td) allseconds = duration.seconds print "The duration is "+str(int(allseconds/60))+"
阅读全文
摘要:3.1计算昨天和明天的日期可以使用datetimie的timedelta方法来表示时间差>>> import datetime>>> today = datetime.date.today()>>> yesteday = today - datetime.timedelta(days=1)>>> tomorrow = today + datetime.timedelta(days=1)>>> print today,yesteday,tomorrow2013-10-29 2013-10-28 2013-1
阅读全文
摘要:2.9 从zip文件中读取数据可以通过Python标准库提供的zipfile模块访问zip压缩文件>>> import zipfile>>> z = zipfile.ZipFile('test.zip','r')>>> for filename in z.namelist(): print 'File:', filenameFile: wex.txtFile: 1.txtFile: a.txt2.16 遍历目录树使用os.walk可以便利目录树>>> for root, di
阅读全文
摘要:2.6 处理文件中的每一词a.先获取每一行,再通过split()方法获取每一个词,之后再进行处理for line in open(thefilepath): for word in line.split(): dosomethingwith(word)b.使用生成器(generator),将元素的迭代,和元素的处理分开def words_of_file(thefilepath, line_to_words=str.split): the_file = open(thefilepath): for line in the_file: for word...
阅读全文
摘要:2.4从文件中读取指定的行从根据给定的行号,从文本中读取一行数据使用python 标准库中linecache模块>>> import linecache>>> theline = linecache.getline('thefile.txt',3)>>> print thelineUsing this simple program as a basis, computer science principles or elements of a specific programming language can be expl
阅读全文
摘要:2.3搜索和替换文件中的文本需要将文件中的某个字符串改变成另外一个。字符串中replace方法提供了字符串替换最简单的办法:>>> s = 'hello world'>>> s.replace('l','L')'heLLo worLd'搜索替换需要两个文件,先第一个文件,再通过replace方法将里面的内容进行铁环,再讲替换完的内容输入到另外一个文件中>>> file_object = open('thefile.txt')>>> file_t
阅读全文
摘要:2.2写入文件a.将一个长字符串写入文件:open('thefile.txt', 'w').write(all_the_text) # text to a text fileopen('abinfile', 'wb').write(all_the_data) # data to a binary fileb.先付给一个对象,处理完毕后在关闭文件file_object = open('thefile.txt', 'w')file_object.write(all_the_text)file_objec
阅读全文
摘要:开始第二章的学习,第二章讲的是python对文件的操作2.1读取文件既然是文件操作,那么就必须先有文件,在如下目录“E:\PythonCookbook\CHA2”创建文件后,在交互模式下发现python无法直接读取文件,文件木有找到>>> all_the_text = open('thefile.txt').read()Traceback (most recent call last): File "", line 1, in all_the_text = open('thefile.txt').read()IOError:
阅读全文
摘要:1.19检查字符串中的结束标记系统有内建函数startswith()和endswith()来检查字符串的开始和结束字符1 >>> s='hello'2 >>> s.endswith('o')3 True4 >>> s.startswith('h')5 True本节使用方法检查字符串S中是否包含多个结束标记中的一个。文中推荐了一种快捷优雅的方法:>>> import itertools>>> def anyTrue(predicate,sequence): r
阅读全文
摘要:1.16替换字符串中的字串给定一个字符串,通过查询一个替换字典,将字典中被标记的子字符串替换掉>>> new_style = string.Template('this is $fst and this is $snd')>>> print new_style.substitute(fst=5,snd=10)this is 5 and this is 10>>> print new_style.substitute({'fst':5,'snd':10})this is 5 and this i
阅读全文
摘要:1.15扩展和压缩制表符tab和空格的互转,一般是tab转空格,一个expandtabs()就足够了,空格转tab可能只出在考试题中s = "a\t aaaaa\t aaaa" s1 = s.expandtabs() print s,len(s) print s1,len(s1) #把空格转成tab def unexpand(s,tablen = 8): import re #切分成空格和非空格 pieces = re.split(r'( +)',s.expandtabs()) #记录当前字符串总长度 len...
阅读全文
摘要:1.14 改变多行文本字符串的缩进>>> def reindent(s,spacenum): leadspace = ' '*spacenum lines = [leadspace+line.strip() for line in s.splitlines()] return '\n'.join(lines)确保文本每一行直接的相对缩进,这样子需要提前计算每一行行首的空格数(下述代码没有按照书中的方式进行处理)>>> def numspaces(s): return [len(line)-len(line.lstrip())
阅读全文