您的位置:首页 > 编程语言 > Python开发

简明python教程的读书笔记(三)

2016-11-27 22:20 260 查看
一、面向对象的编程: 面向过程的编程:根据操作数据的函数或语句块来设计程序的。这被称

为。面向对象的编程:把数据和功能结合起来,用称为对象的东西包裹起来组织程序

的方法。这种方法称为面向对象的 编程理念。类和对象:是面向对象编程的两个主要方面。类创建一个新类型,而对象这个类的实例 。这类似于你有一个int类型的变量,这存储整数的变量是int类的实例(对象)。

怎么创建类:类使用class关键字创建。类的域和方法被列在一个缩进块中。

类的组成:对象可以使用普通的属于 对象的变量存储数据。属于一个对象或类的变量被称为域。对象也

可以使用属于 类的函数来具有功能。这样的函数被称为类的方法。 域有两种类型——属于每个实例/类的对象或属于类本身。它们分别被称为实例变量和类变

量。 self类对象:

类的方法(意思是在类里面定义方法)与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。 创建一个类:

#!/usr/bin/python# Filename:simplestclass.pyclass Person:pass #An empty block表示一个空块p = Person()print p 对象的方法:

类/对象可以拥有像函数一样的方法,这些方法与函数的区别只是一个额外的self变量。#!/usr/bin/python# Filename:method.pyclass Person:def sayHi(self):print 'Hello, howare you?'p = Person()p.sayHi() __init__方法:

__init__方法在类的一个对象被建立时,马上运行。 这个方法可以用来对你的对象做一些你希望的初始化。#!/usr/bin/envpython class person: pass class myob: def __init__(self,name): self.a=1 self.name=name def abc(self): print 'hello,how areyou?',self.a,self.name p=person()print p a=myob('victor')a.abc() 类的变量和对象的变量:

#!/usr/bin/envpython class person: population=0 def __init__(self,name): self.name=name person.population+=1 def howMany(self): print "now there are:",self.population def sayHello(self): '''say hello when add a newperson''' if person.population==1: print 'i am the onlyperson' else: print 'hi, i am new, myname is',self.name def __del__(self): '''i am dying''' print '%s saygoodbye'%self.name person.population-=1 if person.population==0: print 'i am the lastperson' else: print 'still have %sperson left'%person.population p=person('david')p.sayHello()p.howMany() p1=person('davidy')p1.sayHello()p1.howMany() docstring对于类和方法同样有用。我们可以在运行时使用Person.__doc__和Person.sayHi.__doc__来分别访问类与方法的文档字符串。如果你使用的数据成员名称以双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。如果某个变量只想在类或对象中使用,就应该以单下划线前缀。 继承:

。一个子类型在任何需要父类型的场合可以被替换成父类型,即对象可以被视作是父类的实例,这种现象被称为多态现象。我们会发现在重用 父类的代码的时候,我们无需在不同的类中重复它。而如果我们使用独立的类的话,我们就不得不这么做了。在上述的场合中,SchoolMember类被称为基本类 或 超类 。而Teacher和Student类被称为 子类 。如果在继承元组中列了一个以上的类,那么它就被称作多重继承。#!/usr/bin/envpython class School: def __init__(self,name,age): self.name=name self.age=age def tell(self): print 'my name is',self.name print 'my age is %s'%self.ageclassTeacher(School): def __init__(self,name,age,salary): School.__init__(self,name,age) self.salary=salary def tell(self): print 'the teacher salay is%s'%self.salary School.tell(self)classStudent(School): def __init__(self,name,age,mark): School.__init__(self,name,age) self.mark=mark def tell(self): print 'the student mark is%s'%self.mark School.tell(self) a=Teacher('teacherchen',21,20000)b=Student('studentchen',22,90) a.tell()b.tell() 二、输入、输出 创建、读写文件:

完成对文件的操作的时候,你调用close方法来告诉Python我们完成了对文件的使用。注意:不管是写文件或者读文件都需要调用 close方法。模式可以为读模式('r')、写模式('w')或追加模式('a')。事实上还有多得多的模式可以使用,你可以使help(file)来了解它们的详情。#!/usr/bin/envpython def po(): poem='''\abcd efg lalapyton python so goodi love you!!!''' a=file('/poem.txt','w')#指明我们希望打开的文件和模式来创建一个file类的实例。 a.write(poem) a.close() b=file('/poem.txt') while True: line=b.readline() if len(line)==0: break print line b.close()po() 存储器:

Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为持久地 储存对象。 #!/use/bin/en python import cPickle as p mylist=['apple','banana','carot']shoplistfile='shoplist.data'print 'shoplistfileis:',shoplistfileprint 'mylistis:',mylista=file('/root/shoplistfile','w')p.dump(mylist,a)a.close() del mylist#print 'mylistis:',mylistb=file('/root/shoplistfile')mylist2=p.load(b)print 'new listis:',mylist2b.close() 三、异常:try..except

#!/usr/bin/python# Filename:try_except.pyimport systry:s = raw_input('Entersomething --> ')except EOFError:print '\nWhy did youdo an EOF on me?'sys.exit() # exitthe programexcept:print '\nSomeerror/exception occurred.'# here, we are notexiting the programprint 'Done' 如果没有给出错误或异常的名称,它会处理所有的 错误和异常。对于每个try从句,至少都有一个相关联的except从句。 引发异常:

你可以使用raise语句 引发 异常。你还得指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类。你还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。#!/usr/bin/envpython class ShortInputException(Exception):#继承 def __init__(self,length,least): Exception.__init__(self) self.length=length self.least=leasttry: s = raw_input('Enter something -->') if len(s)<3: raiseShortInputException(len(s),3)except EOFError: print '\nWhy did you do an EOF on me?'except ShortInputException,x:#提供了错误类和用来表示错误/异常对象的变量。 print 'ShortInputException: The inputwas of length %d,the expected at least value is %d'%(x.length,x.least) Try finally:

假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件. #!/usr/bin/python# Filename:finally.pyimport timetry: f = file('/poem.txt') while True: # our usual file-readingidiom line = f.readline() if len(line) == 0: break time.sleep(2) print line,finally: f.close() print '\nCleaning up...closed the file' 四、python标准库:Python标准库是随Python附带安装的,它包含大量极其有用的模块。主要讲了2个模块:sys os sys模块:sys模块包含系统对应的功能

有sys.stdin、sys.stdout和sys.stderr分别对应标准输入/输出/错误流。#!/usr/bin/python# Filename: cat.pyimport sysdefreadfile(filename): '''Print a file to the standardoutput.''' f = file(filename) while True: line = f.readline() if len(line) == 0: break print line, # notice comma f.close() if len(sys.argv)< 2: print 'No action specified.' sys.exit() ifsys.argv[1].startswith('--'): option = sys.argv[1][2:] if option == 'version': print 'Version 1.2' elif option == 'help': print 'gouri' else: print 'Unknown option.' sys.exit()else: for filename in sys.argv[1:]: readfile(filename) os模块:

这个模块包含普遍的操作系统功能。这个模块允许即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。● os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。● os.getenv()和os.putenv()函数分别用来读取和设置环境变量。● os.listdir()返回指定目录下的所有文件和目录名。● os.remove()函数用来删除一个文件。● os.system()函数用来运行shell命令。● os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。●os.path.split()函数返回一个路径的目录名和文件名。os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.exists()函数用来检验给出的路径是否真地存在。 五、更多的python内容:列表综合:

#!/usr/bin/python# Filename:list_comprehension.pylistone = [2, 3, 4]listtwo = [2*i for i in listone if i >2]print listtwo 在函数中接收列表或者元组:

当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用*和**前缀。 由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。#!/usr/bin/envpython defpowersum(power,*args): total=0 for i in args: total+=pow(i,power) print total powersum(2,3,4)powersum(2,3) Lambda形式:

lambda语句被用来创建新的函数对象,并且在运行时返回它们。#!/usr/bin/python# Filename:lambda.pydefmake_repeater(n):return lambda s: s*n s表示新函数的参数twice =make_repeater(2)print twice('word')print twice(5) exec和eval语句:

exec语句用来执行储存在字符串或文件中的Python语句。eval语句用来计算存储在字符串中的有效Python表达式:>>>eval('2*3')6assert语句:

assert语句用来声明某个条件是真的。>>> mylist= ['item']>>> assertlen(mylist) >= 1>>> mylist.pop()'item'>>> assertlen(mylist) >= 1Traceback (mostrecent call last):File"<stdin>", line 1, in ?AssertionError repr函数:

repr函数用来取得对象的规范字符串表示。 六、最后,我们来编写一个程序:创建你自己的命令行地址簿 程序。在这个程序中,你可以添加、修改、删除和搜索(字典方法的使用)你的联系人(朋友、家人和同事(类的使用)等等)以及它们的信息(诸如电子邮件地址和/或电话号码)。这些详细信息应该被保存下来(cPickle)以便以后提取。 自己写的很仓促,还缺乏交互性等一些优化。#!/usr/bin/envpython import cPickle as pclass people: zidian={} print 'initiated dic is',zidian def add(self,name,mobile): people.zidian[name]=mobile a=file('/root/zidian.txt','w') p.dump(people.zidian,a) a.close() print 'after add one person,the dic is',people.zidian def upd(self,name,mobile): people.zidian[name]=mobile a=file('/root/zidian.txt','w') p.dump(people.zidian,a) a.close() print 'after update one person,the dic is',people.zidian def dele(self,name): del people.zidian[name] print 'after delete the dicitmes:',people.zidian def query(self,name): if people.zidian.has_key(name): print '%s mobile is%s'%(name,people.zidian[name]) else: print 'no informationabout this person' person=people()person.add('chen','13912344')person.add('zu','14')person.upd('chen','123')person.dele('zu')person.query('chen')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  读书笔记 python 简明