Python基础学习笔记四

Python基础学习笔记四

类和对象:

如果创建新式类,则应该让类继承object,如class test(object):

Python中继承使用()来表示,允许多重继承

Python的类的方法,必须有一个参数self

私有化:在方法和属性前加两个下划线

构造方法:__init__(self)

子类调用父类的方法:super(子类名称,self).__init__()#调用父类构造方法

异常处理:

try…except….finally

raise人为引发异常

访问器及property

class Test(object):

    def __init__(self):

        self.height=0

        self.width=0

    def setSize(self,size):

        self.height,self.width=size

    def getSize(self):

        return self.height,self.width

    size=property(getSize,setSize)

 

t=Test()

print t.size

t.size=10,20

print t.size

静态方法和类方法:

使用@staticmethod来定义静态方法,不需要任何参数

使用@classmethod来定义类方法,参数使用cls而不是self

模块:

__name__==’__main__’#判断是否为主方法

sys.path#路径信息

pprint.pprint#分行打印

dir(模块名称)#列出模块中的信息

:

一个文件夹下,有__init__.py文件,那么这个文件夹就可以成为包

help(模块|模块方法)

模块名.__file__#获取模块的标准源代码

标准库:

sys:sys.path

os:

os.system(系统命令)

集合:

set(列表),如set(range[1,10])

列表可以计算交集并集之类

堆:

双端队列:

time模块:

time.time()#获取当前时间戳

time.mktime(2011,1,20,10,10,20,0,0,0)#根据给定时间获得时间戳

random模块:

random.random()#返回0到1之间的随机数

random.rangerandom(min,max,step)#返回range(min,max,step)中的随机数

random.choice(seq)#返回序列的随意元素

shelve模块:

import shelve

data=shelve.open("hi.data")

data["x"]=['1','2','3','4']

print data['x']

data.close()

shelve同样也会建立文件,类似于读写操作相结合

re模块:

re.compile(正则表达式)#根据正则表达式创建模式对象

search(string)#搜索

match()#匹配

findall()#查找全部,并返回列表

split()#分割

sub()#替换

文件操作:

打开文件:open(filename,mode)

#mode模式如下列表

r读模式

w写模式

a追加模式

b二进制模式

+读写模式

读操作:

handle.read()#读入全部

handle.readline()#读入一行

handle.randlines()#作为列表分行读入

with操作的重要性:

with需要导入,from __future__ import with_statement

with open(filename) as somefile:

      dowork(somefile)

这样即使出现异常,也能保证文件被正常关闭

fileinput:迭代操作

for line in fileinput.input(filename):

      print line

实现整个文件按行迭代

 

posted @ 2011-07-03 11:44  rorshach  阅读(150)  评论(0编辑  收藏  举报