本次包含面向对象、文件操作部分
面向对象的编程
属于一个对象或类的变量被称为域。域和方法可以合称为类的属性。
域的两种类型–属于每个实例/类的对象或属于类本身。它们分别被称为实例变量和类变量。
类的方法与普通的函数只有一个特别的区别–他们必须有一个额外的第一个参数名称,但是在调用这个方法的时刻可以不为这个参数赋值,默认名称为self,相当于Java中的this
class Person: pass # An empty block p = Person() #没有new print(p)
带方法的
class Person: def sayHi(self): #必须带参数self表示自身,如果包含多个参数,self必须为第一个 print('Hello, how are you?') p = Person() p.sayHi() #== Person().sayHi();
带参的构造函数
通过__init__方法来实现
__init__方法在类的一个对象被建立时马上执行。开始和结尾都是双下划线。
类的变量由一个类的所有对象(实例)共享使用,只是一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其它的实例上。
__del__ 相当于虚构函数
class Person: number=0 #类变量 def __init__(self,name): print('new Person, name is',name) self.name=name #实例变量 Person.number+=1 #只能通过类名.类变量的这种方式来使用 def __del__(self): print('Person has destoryed, name is', self.name) Person.number-=1 ivy = Person('ivy') lance = Person('lance') del lance del ivy
约束,Python中所有的类成员(包括数据成员)都是公共的,所有的方法都是有效的,但有一个例外就是:如果使用的数据成员名称以双下划线前缀比如__privateVar(此时后缀不能为双下划线),Python的名称管理体系会有效地把它作为私有变量。
惯例:如果某个变量只想在类中或对象中使用就应该以单下划线为前缀。
继承,重用
class ChildClass(ParentClass): '''Represent Child Class.''' def __init__(self,name,grade): ParentClass.__init__(self, name) # 调用父类方法时用类似类变量的方式调用 self.name = name def show(self): ParentClass.show(self) print('Name is', name)
Python不会自动调用父类的constructor,得自己调用一下。
输入输出
f=open('filepath','filemode',buffering=-1,'encoding') f = open('c:/ivy.txt','w') f.write('this is written by python') f.flush() f.close()
#打开的模式
#r 读(默认) w truncate写 a 追加 b 二进制 t 文本(默认) + 打开并更新(有追加的意思,reading and writing) U newLineMode
open返回的类会因打开的模式不同而有差异。
text mode(r, w, rt, wt)-> TextIOWrapper
binary mode(rb)->BufferedReader
binary mode(wb)->BufferedWriter
binary mode(w+b)->BufferedRandom
f=open('c:/python_io.txt','r+') print(f.__class__) f.close() f=open('c:/python_io.txt','r+b') print(f.__class__) f.close() f=open('c:/python_io.txt','w+b') print(f.__class__) #可以看实现类是啥,执行help(f)可看api f.close()
存储器
模块:pickle与cPickle,都是用于持久化对象,用其可以在一个文件中存储任何Python对象,之后又可以把它完整无缺地取出来。区别,cPickle用C写的,比pickle快1000倍
import pickle as p #这样就可以用别名了 目前从官网上下的标准没带cPickle模块 shoplist=['apple', 'mango', 'carrot'] shoplistfile='c:/shoplist.data' f=open(shoplistfile,'wb') #二进制写模式,可以采用ab的方式进行追加 p.dump(shoplist,f) f.flush() #最好flush下,直接close()的话偶尔恢复不回来了 f.close() f=open(shoplistfile,'rb') storedlist=p.load(f) f.close() print(storedlist)
待续……