Python 简明教程学习笔记

10年前
数据结构()  list用法:     shoplist = ['apple', 'mango', 'carrot', 'banana']   len(shoplist)   for item in shoplist:   shoplist.append('rice')   shoplist.sort()   shoplist[0]    元组   zoo = ('wolf', 'elephant', 'penguin')   len(zoo)   new_zoo = ('monkey', 'dolphin', zoo)   new_zoo[2][2]表示企鹅   new_zoo[2]表示zoo这个元组    字典   ab = {       'Swaroop'   : 'swaroopch@byteofpython.info',                'Larry'     : 'larry@wall.org',                  'Matsumoto' : 'matz@ruby-lang.org',                  'Spammer'   : 'spammer@hotmail.com'          }   ab['Guido']   del ab['Spammer']   for name, address in ab.items():   if 'Guido' in ab:  序列   索引   shoplist[0] 【0】作为该LIST得索引      切片   shoplist[0:1] 【0:1】作为切片表示从0开始1结束  参考   mylist=shoplist  mylist作为shoplist的副本,mylist的item改变不会影响shoplist,而shoplist改变则会影响mylist    字符串   name='Swaroop'   if name.startswith('Swa'):   if 'a' in name:   if name.find('war')!=-1:    面向对象()    类使用class关键字创建。类的域(变量)和方法被列在一个缩进块中。  类的方法和普通函数只有一个区别,类的方法必须有一个额外的第一个参数的名称,但是在调用这个方法的时候你不为这个参数赋值,由PYTHON提供这个值,这个特别的变量指对象本身,按照惯例他的名称是self  有一个类MyClass和这个类的对象MyObject :MyObject.method(arg1,arg2)的时候python自动转化为MyClaa.method(MyObject,arg1,arg2)     创建一个类:   class Person:    pass # An empty block   p=Person()   print p   输出:<__main__.Person instance at 0xf6fcb18c>   可以注意到存储对象的计算机内存地址打印出来了,因为Python可以在任何空位存储对象     使用对象的方法:   class Person:    def sayHi(self):     print 'hello,how are you?'   p=person()   p.syaHi()   注意:sayHi方法没有任何参数,但仍然在函数定义时有self。     __init__方法和__del__方法   class Person:    def __init__(self,name):     self.name=name    def sayHi(self):     print 'hello,my name is',self.name   p=Person('Swaroop')   p.sayHi()   输出:hello,my name is Swaroop   __init__()方法,只是在创建类的新实例的时候,把参数包括在括号内跟在类名后面,从而传递给_init()方法。ps相当于:java中的构造函数      __del__()方法,在对象消逝的时候调用    类和对象的方法:   类的变量和对象的变量不同:对象的变量赋值如"self.name" 而类的变量"name"      所有的类成员都是公共的   但以双下划线为前缀的数据成员如:__a,Python会有效的把他作为似有变量.   惯例:如果某个变量只想在类和对象中使用,就应该以单下划线为前缀。  继承:   class SchoolMember:    def __init__(self,name,age):     self.name=name     self.age=age     print '(Initialized SchoolMember:%s)'%self.name    del tell(self):     print 'Name:"%s" Age:"%s"'%(self.name,self.age)      class Teacher(SchoolMember):    def __init__(slef,name,age,salary)     SchoolMember.__init__(self,name,age)     self.salary=salary    del tell(self):     SchoolMember.tell(self)     print'salary:"%d"'%slef.salary     __init__方法专门使用self变量调用,这样我们就可以初始化对象的基本类部分。   这一点十分重要——Python不会自动调用基本类的constructor,必须手动自己调用。   如果在继承元组中列了一个以上的类,那么它就被称作 多重继承      输入输出()  raw_input和print  输入和输出:     文件:   file类的对象来打开一个文件,分别使用file类的方法read,readline,write方法来恰当的读写文件,完成对文件的操作时,调用close方法   poem='''write into file's content'''   f=file('poem.txt','w')   f.write(poem)   f.close()   f=file('poem.txt')   while True:    line=f.readline()    if len(line)==0:     break    print line   f.close()   注意:只读模式'r',写入模式'w',追加模式'a',不指定为只读模式.  存储器(pickle):   pickle和cPickle的区别,功能相同,cPickle(C语言写的)比pickle更快      import cPickle as p   shoplistfile='shoplist.data'   shoplist = ['apple', 'mango', 'carrot']   f = file(shoplistfile, 'w')   p.dump(shoplist,f)#dump the object to a file   f.close()   del shoplist      f=file(shoplistfile)   storedlist=p.load(f)   print storedlist  异常()  try..except:   import sys     try:        s = raw_input('Enter something --> ')   except EOFError:        print '\nWhy did you do an EOF on me?'        sys.exit() # exit the program   except:        print '\nSome error/exception occurred.'        # here, we are not exiting the program   print 'Done'      将有可能发生错误的语句放入try:语句中,用except:来处理这些错误,对于每一个try从句至少有一个except从句与其关联  引发异常:   raise语句   class ShorInputException(Exception):    def __init__(self,length,atleast):     Exception.__init__(self)     self.length=length     self.atleast=atleast   try:    s=raw_input('Enter something-->')    if len(s)<3:     raise ShorInputException(len(s),3)   except EOFError:    print '\nWhy did you do an EOF on me?'   except ShorInputException,x:    print 'ShortInputException: The input was of length %d, \            was expecting at least %d' % (x.length, x.atleast)   else:    print 'No exception was raised'  try...finally:      Python标准库()  sys模块:    os模块:   os.name返回操作系统平台   os.getcwd()返回当前工作目录   os.getenv(),os.putenv读取和设置环境变量   os.listdir返回指定目录下的所有文件和目录名   os.remove() 删除一个文件   os.system()用来运行shell命令   os.linesep字符串给出当前平台的行终止符,windows-'\r\n'linx-'\n'mac-'\r'   os.path.split()返回一个路径的目录名和文件名   os.path.isfile(),os.path.isdir()分别检测是文件还路径   os.path.existe用来检测给出的路径是否存在    更多()  特殊的方法:   __init__()   __del__()   __getitem__()可以用来获取元组或list相对位置的值  在函数中接收元组和列表:   当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用*和**前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。   def powersum(power, *args):    total=0    for i in args:     total+=pow(i,power)    return total   >>> powersum(2,3,4)    25   >>> powersum(2,10)   100   由于args变量前有*前缀,所有多余的函数参数都会作为一个元组存在args中,如果**为前缀,那么对于的参数会被认为是字典的键/值对  lambda形式:   def make_repeater(n):    return lambda s:     s*n   twice=mak_repeater(2)   print twice('word')   print twice(5)   输出:wordword        10   注意:lambda语句用来创建函数对象,lambda需要一个参数(s)这个参数作为函数体,而表达式的质被这个新建的函数返回。注意即便是print语句也不能用在lambda形式中,只能使用表达式.   猜想:  exec和eval语句:   >>>exec 'print "hello world"'   hello world   >>>eval('2*3')   6   exec用来执行存储在文件或字符串中的python语句   eval用来执行存储在字符串中的python表达式