Python学习笔记

Python学习笔记

1.基础知识

·       用于实现整除的操作符://

·       幂运算符:**

·       Python中变量没有类型。类型的强制转换使用函数int(32.9);而C中强制转换使用(int)32.9

·       round():将浮点数四舍五入;floor():向下取整;ceil():向上取整

·       跨多行的字符串使用三个引号”””zhang”””’’’zhang’’’;或者每行最后加反斜线\

·       在字符串前加r表示为原始字符串:r”python”。原始字符串不会把反斜线当作特殊字符,在其中输入的每个字符都会与书写的方式保持一致。

>>> print r'This is illegal\'

SyntaxError: EOL while scanning string literal

>>> print r'This is illegal\\'

This is illegal\\

2.列表与元组

注意:列表可以修改,而元组和字符串不可以修改。列表方法会直接原地修改列表,而元组和字符串方法方法只会生成修改后的副本。

2.1.  序列通用操作

·       分片:[1:10],[:10],[1:],[-3:],[:],[10:0:-2],[::4]

·       加法:序列的连接操作;乘法:序列扩倍

>>> [1,2,3]+[4,5,6]

[1, 2, 3, 4, 5, 6]

>>> [1,2,3]*3

[1, 2, 3, 1, 2, 3, 1, 2, 3]

·       in运算符检查成员资格

·       len,max,min分别求长度,最大值和最小值

2.2.  列表

·       list()将序列转换为列表

·       del name[2] 删除元素

·       分片赋值:

name[2:] = list(‘ilei’)

#增加元素

>>> numbers = [1,5]

>>> numbers[1:1] = [2,3,4]

>>> numbers

[1, 2, 3, 4, 5]

#删除元素

>>> numbers[1:4] = []

>>> numbers

[1, 5]

·       列表方法:append,count,extend,index,insert,pop,remove,reverse,sort。可模仿下图查看方法的具体功能。

clip_image001

·       使用关键字参数cmp,key,reverse进行高级排序:

>>> x=['zhang','lei','leii']

>>> x.sort(key=len)

>>> x

['lei', 'leii', 'zhang']

>>> x=[4,6,3,8,9]

>>> x.sort(reverse=True)

>>> x

[9, 8, 6, 4, 3]

>>> x=[4,6,3,8,9]

>>> x.sort(cmp)

>>> x

[3, 4, 6, 8, 9]

2.3.  元组

·       如果用逗号分隔了一些值,那么就自动创建了元组。

·       tuple()函数将序列转换为元组

3.字符串

·       字符串格式化

>>> "zhang %s lei" % 'lei'

'zhang lei lei'

>>> "zhang %s %s" % ('lei','lei')#只能是元组或者字典,不能是列表

'zhang lei lei'

>>> '%*.*f'%(10,2,3.1415926)

'      3.14'

>>> '%10.2f'% 3.1415926

'      3.14'

·       字符串常量

string.digits,string.letters,string.lowercase,string.uppercase,string.printable,string.punctuation

·       字符串方法:find,join,lower,replace,split,strip,translate

>>> import string

>>> table = string.maketrans(string.lowercase,string.uppercase)

>>> 'zhangleilei'.translate(table)

'ZHANGLEILEI'

>>> '*/*/**/py**/t/*hon*/*/*///'.strip('/*')

'py**/t/*hon'

4.字典

注意:字典中并无最后的元素或其他有关顺序的概念。

·       dict()通过键值序列对或者关键字参数创建字典

·       字典的格式化字符串:

>>> d = {'John':90,'Andy':99,'Joe':60}

>>> "Joe's grade is %(Joe)d." % d

"Joe's grade is 60."

·       字典方法:clear,copy,fromkeys,get,has_key,items,iteritems,keys,iterkeys,values,itervalues,pop,popitem,setdefault,update

5.条件、循环和其他语句

5.1.  print:逗号变空格

>>> print 'zhang','leilei'

zhang leilei

5.2.  import

>>> import math

>>> from math import sqrt

>>> sqrt(9)

3.0

>>> from math import sqrt as func

>>> func(9)

3.0

>>> import math as func

>>> func.sqrt(9)

3.0

5.3.  赋值(逗号连起来的数组成序列,下述操作称为序列解包)

>>> x,y,z = 1,2,3

>>> print x,y,z

1 2 3

>>> x,y = y,x

>>> print x,y,z

2 1 3

>>> d = {'John':90,'Andy':99,'Joe':60}

>>> key,value = d.popitem()

>>> print key,value

John 90

>>> x=y=z=99

>>> print x,y,z

99 99 99

5.4.  条件语句

1)         为假的内容:False,None,0,空序列,空字典

2)         is:同一性运算符;==:相等运算符;and,or,not:布尔运算符

>>> 0 and 2+3

0

>>> 1+2 and 2+3

5

>>> 0 or 1+2

3

>>> 1+2 or 0

3

>>> not 1+3

False

3)         三元运算符

>>> 'Yes' if 1>2 else 'No'

'No'

5.5.  断言,确保程序中的某个条件为真才能让程序正常工作。

>>> age = 10

>>> assert 0<age<100 ,"Pay attention to the range!"

>>> age = -1

>>> assert 0<age<100 ,"Pay attention to the range!"

 

Traceback (most recent call last):

  File "<pyshell#66>", line 1, in <module>

    assert 0<age<100 ,"Pay attention to the range!"

AssertionError: Pay attention to the range!

5.6.  for循环

>>> #序列解包

>>> d = {'x':1,'y':2,'z':3}

>>> for key,value in d.items():

print key ,'is' , value

 

 

y is 2

x is 1

z is 3

>>> #并行迭代1

>>> names = ['Joe','Grace','John']

>>> ages  = [10,12,6]

>>> for i in range(len(names)):

print names[i],'is',ages[i],'years old!'

 

 

Joe is 10 years old!

Grace is 12 years old!

John is 6 years old!

>>> #并行迭代2

>>> for name,age in zip(names,ages):

print name ,'is',age,'years old!'

 

 

Joe is 10 years old!

Grace is 12 years old!

John is 6 years old!

>>> zip(names,ages)#zip()将两个序列压缩在一起,然后返回一个元组的列表

[('Joe', 10), ('Grace', 12), ('John', 6)]

>>> #编号迭代

>>> for index,name in enumerate(names):

if 'J' in name:

    names[index] = 'feynman'

 

   

>>> names

['feynman', 'Grace', 'feynman']

>>> enumerate(names)#enumerate()在提供索引的地方迭代索引值对

<enumerate object at 0x01F05800>

5.7.  while True/break

5.8.  轻量级循环——列表推导式(利用其它列表创建新列表)

>>> [x*x for x in range(10)]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> [x*x for x in range(10) if x > 5]

[36, 49, 64, 81]

>>> [(x,y) for x in range(3) for y in range(3)]

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

>>> boys = ['alice','bernice','clarice']

>>> girls = ['chris','arnold','bob']

>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]

['alice+arnold', 'bernice+bob', 'clarice+chris']

6.函数

6.1.文档字符串

>>> def func(x):

'Calculate f(x)'

return 2*x

 

>>> func(5)

10

>>> func.__doc__

'Calculate f(x)'

6.2.参数

1)   列表作为形参时,列表的值可以在函数中被修改。

2)   关键字参数,(提供形参的名字,同时可以为参数提供默认值)

>>> def hello(greeting = 'Hello',name = 'world'):

print greeting,name,'!'

 

 

>>> hello()

Hello world !

>>> hello('Hi')

Hi world !

>>> hello('Hey','Joe')

Hey Joe !

>>> hello(name = 'Grace')

Hello Grace !

3)   收集参数:’*’把收集的参数作为元组;’**’把收集的关键字参数作为字典

>>> def f(p1,*p):

print p1

print p

 

 

>>> f('zhang',1,2,3)

zhang

(1, 2, 3)

>>> f('zhang',1)

zhang

(1,)

>>> f('zhang')

zhang

()

>>> def ff(p1,**p):

print p1

print p

 

 

>>> ff('zhang',name='Joe',age=5)

zhang

{'age': 5, 'name': 'Joe'}

>>> ff('zhang')

zhang

{}

反转过程:’*’把元组作为位置参数;’**’把字典作为关键字参数

>>> def withstars(**kwds):

print kwds['name'],'is',kwds['age'],'years old!'

 

 

>>> def withoutstars(kwds):

print kwds['name'],'is',kwds['age'],'years old!'

 

 

>>> args = {'name':'Joe','age':5}

>>> withstars(**args)

Joe is 5 years old!

>>> withoutstars(args)

Joe is 5 years old!

6.3.作用域

1)  变量和所对应的值用的是一个不可见的字典,内建的vars()函数可以返回这个字典。

>>> x,y,z = 1,2,3

>>> vars()['x']

1

2)  每次函数调用会创建新的作用域。如果全局变量和局部变量的名字相同,可以使用globals()获取全局变量的值。

>>> def f(x):

return x+globals()['x']

 

>>> f(5)

6

3)  如果想在函数中修改全局变量的值,必须使用global对全局变量进行声明。假如在函数内部将值赋予一个变量,它会自动成为局部变量,除非使用global对其进行声明

>>> def g():

global x

x += 1

 

 

>>> x

1

>>> g()

>>> x

2

7.类和对象

7.1.基本概念

对象:数据以及由一系列可以存取、操作这些数据的方法所组成的集合。

类:所有的对象都属于某一个类,称为类的实例。类名使用单数名词,且首字母大写。

# -*- coding: cp936 -*-

__metaclass__ = type #确定使用新式类

 

class Person:

    defsetName(self,name):

        self.name = name

    defgetName(self):

        return self.name

    defgreet(self):

        print"Hello,world! I am %s."% self.name

>>> zhang=Person()

>>> Joe=Person()

>>> zhang.setName('leilei')

>>> Joe.setName('SanFeng')

>>> zhang.getName()

'leilei'

>>> Joe.getName()

'SanFeng'

>>> zhang.greet()

Hello,world! I am leilei.

>>> Joe.greet()

Hello,world! I am SanFeng.

上例中,Personzhang,Joe为类的实例,即对象

setName,getName,greet方法,方法与函数唯一的区别是self参数。方法总是将对象作为自己的第一个参数,即self.

name变量为特性。特性可以在类的外部访问。

>>> zhao=Person()

>>> zhao.name = 'Qingxue'

>>> zhao.greet()

Hello,world! I am Qingxue.

如果在类的第3行定义中,将self.name = name改为Person.name = name,则在第一次调用setName之后,类的所有实例的name特性均被赋值。

>>> zhang=Person()

>>> zhang.setName('leilei')

>>> Joe=Person()

>>> Joe.name

'leilei'

7.2.继承:将类名写在class语句后的圆括号内即可指定超类,子类可以继承超类的方法。

# -*- coding: cp936 -*-

__metaclass__ = type #确定使用新式类

 

class Filter():

    definit(self):

        self.blocked =[]

    deffilter(self,sequence):

        return[x for x in sequence if x notin self.blocked ]

 

class SpamFilter(Filter):

    definit(self):

        self.blocked =['Spam']

>>> spamfilter = SpamFilter()

>>> spamfilter.init()

>>> spamfilter.filter(['Spam','zhang','Joe'])

['zhang', 'Joe']

子类的基类可以多于一个,当多个基类中含有同名的方法时,先继承的基类中的方法会屏蔽后继承基类的方法。

7.3.一些函数

issubclass():查看一个类是否另一个类的子类

isinstance():查看一个对象是否一个类的实例

__bases__:查看已知类的基类

__class__:查看一个对象属于哪个类

hasattr():查看某对象是否具有某方法

>>> issubclass(SpamFilter,Filter)

True

>>> issubclass(Filter,SpamFilter)

False

>>> isinstance(spamfilter,SpamFilter)

True

>>> isinstance(spamfilter,Filter)

True

>>> SpamFilter.__bases__

(<class '__main__.Filter'>,)

>>> spamfilter.__class__

<class '__main__.SpamFilter'>

>>> hasattr(spamfilter,'filter')

True

>>> hasattr(spamfilter,'filte')

False

8.异常

8.1.  什么是异常

>>> 1/0

 

Traceback (most recent call last):

  File "<pyshell#49>", line 1, in <module>

    1/0

ZeroDivisionError: integer division or modulo by zero

可以直接用raise引发异常:

>>> raise Exception

 

Traceback (most recent call last):

  File "<pyshell#51>", line 1, in <module>

    raise Exception

Exception

8.2.  Python中用异常对象表示异常情况。每个异常对象都是某个类的实例。

Python中所有的异常类可以使用dir()函数列出:

>>> import exceptions

>>> dir(exceptions)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception',……]

除了内建异常类之外,还可以自定义异常类,但必须从Exception类继承。

8.3.  捕捉异常

try/except/else/finally

whileTrue:

    try:

        x = input("The 1st number:")

        y = input("The 2nd number:")

        print'%d / %d = %d'%(x,y,x/y)

    except:

        print"Invalid input,try again!"

    else:

        break

    finally:

        print"It's over."

try子句发生异常时,执行except子句,否则执行else子句。finall子句肯定会被执行,不管try子句中是否发生异常。

>>>

The 1st number:20

The 2nd number:0

Invalid input,try again!

It's over.

The 1st number:20

The 2nd number:*

Invalid input,try again!

It's over.

The 1st number:20

The 2nd number:5

20 / 5 = 4

It's over.

>>> 

except后可以跟异常类型,当捕捉到不同的异常时,执行不同的子句。当except后无异常类型时,except可以捕捉所有的异常:

except ZeroDivisionError

except TypeError:

except (ZeroDivisionError, TypeError):

except:

whileTrue:

    try:

        x = input("The 1st number:")

        y = input("The 2nd number:")

        print'%d / %d = %d'%(x,y,x/y)

    except TypeError:

        raise

    except ZeroDivisionError,e:     #可以通过e打印错误信息

        print e,",try again!"

    finally:

        print"It's over."

except子句可以连用,同时捕捉多个异常;

except子句捕捉到异常后,若想重新引发该异常,使用不带参数的raise

except子句的第二个参数可以用来打印错误信息;

finally子句在引发异常前执行。

>>>

The 1st number:20

The 2nd number:0

integer division or modulo by zero ,try again!

It's over.

The 1st number:20

The 2nd number:'x'

It's over.

 

Traceback (most recent call last):

  File "E:/学习/Python/20140719.py", line 8, in <module>

    print '%d / %d = %d' % (x,y,x/y)

TypeError: unsupported operand type(s) for /: 'int' and 'str'

>>> 

9.构造方法、属性和迭代器

9.1.为了确保类是新型的,应该把赋值语句__metaclass__ = type 放在模块的最开始,或者子类化内建类object

9.2.构造方法:对象被创建时,会自动调用的方法。只需要把init改为__init__即可。

1

__metaclass__ = type

 

class Foobar:

    def__init__(self):

        self.someval =42

>>> foobar = Foobar()

>>> foobar.someval

42

2

__metaclass__ = type

 

class Foobar:

    def__init__(self,value):

        self.someval = value

>>> foobar = Foobar('zhang')

>>> foobar.someval

'zhang'

9.3.构造方法的继承与重写

__metaclass__ = type

 

class Bird:

    def__init__(self):

        self.hungry =True

 

    defeat(self):

        if self.hungry ==True:

            print"Aaaah..."

            self.hungry =False

        else:

            print"No,thanks."

 

class SongBird(Bird):

    def__init__(self):

        self.sound ="Squawk!"

 

    defsing(self):

        print self.sound       

>>> bird = Bird()

>>> bird.eat()

Aaaah...

>>> bird.eat()

No,thanks.

>>> songbird = SongBird()

>>> songbird.sing()

Squawk!

>>> songbird.eat()

 

Traceback (most recent call last):

  File "<pyshell#68>", line 1, in <module>

    songbird.eat()

  File "E:/学习/Python/20140719.py", line 8, in eat

    if self.hungry == True:

AttributeError: 'SongBird' object has no attribute 'hungry'

问题:SongBird虽然继承了Bird中的eat方法,但是由于SongBird重写了构造方法,导致SongBird没有hungry特性。为了达到预期的效果,SongBird的构造方法中必须调用其超类的构造方法来确保进行基本的初始化。

有两种解决方法:

1)  调用超类构造方法的未绑定版本

class SongBird(Bird):

    def__init__(self):

        Bird.__init__(self)

        self.sound ="Squawk!"

 

    defsing(self):

        print self.sound   

绑定与未绑定的区别:

绑定:Bird.__init__(self),Bird为类,self未指定任何对象,可任意指定

未绑定:bird.__init__(self),bird为对象,self代表bird

2)  使用super函数

class SongBird(Bird):

    def__init__(self):

        super(SongBird,self).__init__()

        self.sound ="Squawk!"

 

    defsing(self):

        print self.sound

注意:定义的时候有self,__init__(self),而调用的时候没有self,__init__()

经过修改之后:

>>> songbird = SongBird()

>>> songbird.eat()

Aaaah...

>>> songbird.eat()

No,thanks.

9.4.子类化列表、字典和字符串

例:重写列表的部分方法,使其具有访问计数功能

__metaclass__ = type

 

class LList(list):

    def__init__(self,*args):

        super(LList,self).__init__(*args)

        self.counter =0

 

    def__getitem__(self,key):

        self.counter +=1

        return super(LList,self).__getitem__(key)

>>> ll = LList(range(10))

>>> ll

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> ll.counter

0

>>> ll[1]+ll[2]+ll[5]

8

>>> ll.counter

3

9.5.属性

class Rectangle(object):

    def__init__(self):

        self.width =0

        self.height =0

 

    defgetSize(self):

        return self.width,self.height

 

    defsetSize(self,size):

        self.width,self.height = size

 

    defdelSize(self):

        del self.width,self.height

 

    size = property(getSize,setSize,delSize,"Parameters of rectangle!")

可以通过命令help(property)查看属性的有关内容。

通过getx,setx,delx定义的方法称为属性,并在类定义的最后一行增加property的调用:x = property(getx,setx,delx,"I'm the 'x' property.")property函数的四个参数均可选。用法示例如下:

>>> r = Rectangle()

>>> r.getSize()

(0, 0)

>>> r.setSize((55,100))

>>> r.getSize()

(55, 100)

>>> r.size

(55, 100)

>>> r.size = (23,319)

>>> r.size

(23, 319)

9.6.其它一些魔法方法

__getattribute__(self,name):当特性name被访问时自动被调用

__getattr__(self,name):当特性name被访问且对象没有相应的特性时被自动调用

__setattr__(self,name,value):当试图给特性name赋值时被自动调用

__delattr__(self,name):当试图删除特性name时被自动调用

例:

class Rectangle(object):

    def__init__(self):

        self.width =0

        self.height =0

 

    def__getattr__(self,name):

        if name =='size':

            return self.width,self.height

        else:

            raise AttributeError

 

    def__setattr__(self,name,value):

        if name =='size':

            self.width,self.height = value

        else:

            self.__dict__[name]= value

>>> r = Rectangle()

>>> r.height

0

>>> r.size

(0, 0)

>>> r.size = (12,53)

>>> r.height

53

>>> r.size

(12, 53)

对象r只有heightwidth两个特性,没有size特性。但是可以通过r.size访问到heightwidth两个特性。

9.7.迭代器

含有__iter__方法和next方法的对象。

1)   可以使用内建的iter函数创建

>>> f = iter([1,1,2,3,5,8,11,19])

>>> f

<listiterator object at 0x01FF81D0>

>>> f.next()

1

>>> f.next()

1

>>> f.next()

2

>>> f.next()

3

2)   自定义迭代器

例:斐波那契数列的实现

class Fibs:

    def__init__(self):

        self.a =0

        self.b =1

    defnext(self):

        self.a,self.b = self.b,self.a+self.b

        return self.a

    def__iter__(self):

        return self

>>> f = Fibs

>>> f = Fibs()

>>> f.next()

1

>>> f.next()

1

>>> f.next()

2

>>> for n in f:

    if n > 1000:

       print n

       break

 

   

1597

当迭代器中的数据有限时,可以用list将所有数据列出。

class Fibs:

    def__init__(self,sum):

        self.a =0

        self.b =1

        self.sum = sum

    defnext(self):

        self.sum -=1

        self.a,self.b = self.b,self.a+self.b

        if self.sum >=0:

            return self.a

        else:

            raise StopIteration

    def__iter__(self):

        return self

>>> fibs = Fibs(10)

>>> fibs.next()

1

>>> fibs.sum

9

>>> fibs.next()

1

>>> fibs.next()

2

>>> list(fibs)

[3, 5, 8, 13, 21, 34, 55]

>>> fibs.next()

 

Traceback (most recent call last):

  File "<pyshell#23>", line 1, in <module>

    fibs.next()

  File "E:/学习/Python/20140720", line 12, in next

    raise StopIteration

StopIteration

9.8.生成器

1)   生成器:用普通的函数语法定义的迭代器。

例:用于展开两层列表的函数

defflatten(nested):

    for sublist in nested:

        for element in sublist:

            yield element

>>> nested = [[1,2,3,4],[5,6],[7]]

>>> flatten(nested)

<generator object flatten at 0x01F30C10>

>>> F = flatten(nested)

>>> F.next()

1

>>> F.next()

2

>>> list(F)

[3, 4, 5, 6, 7]

生成器是一个包含yield关键字的函数。当它被调用时,在函数体中的代码不会被执行,而会返回一个迭代器。每次请求一个值,就会执行生成器中的代码,直到遇到一个yieldreturn语句。yield语句意味着应该生成一个值。return语句意味着生成器要停止执行。

2)   生成器推导式

列表推导式返回列表,生成器推导式返回生成器;列表推导式使用[],生成器推导式使用().

>>> (i*i for i in range(5))

<generator object <genexpr> at 0x01F30C10>

>>> g = (i*i for i in range(5))

>>> g.next()

0

>>> g.next()

1

>>> list(g)

[4, 9, 16]

>>> sum(i*i for i in range(5))

30

3)   递归生成器

例:可以展开任意层列表的函数

defflatten(nested):

    try:

        for sublist in nested:

            for element in flatten(sublist):

                yield element

    except TypeError:

        yield nested

>>> nested = [[[1,2,3],4],[5,6],7]

>>> list(flatten(nested))

[1, 2, 3, 4, 5, 6, 7]

10.模块

10.1  任何Python程序都可以作为模块导入。

#hello.py

 

defhello():

    print"Hello,world!"

 

deftest():

    hello()

 

if __name__ =='__main__':

    test()

上例在模块中增加了用于测试模块本身是否可以正常工作的代码。当上述代码作为程序运行时,test()函数被执行;当作为模块导入时,test()函数不会被执行。这是由于__name__变量的作用,在主程序中,__name__的值为__main__,而在导入的模块中,__name__的值为模块的名字。

为使编译器能找到模块,有两种方法:

l  编辑sys.path

>>> import sys

>>> sys.path.append("E:\学习\Python")

>>> import hello

>>> hello.hello()

Hello,world!

l  将模块所在目录加至用户变量PYTHONPATH中。

10.2 

将许多模块放在同一个文件夹内,将这些模块组织为包。为了让Python将其作为包对待,包内必须包含一个名为__init__.py的模块。

例:假如包constants中包含模块__init__.py,power.py,add.py

import constants:只有__init__.py模块可用;

import constants.power:__init__.py模块和power.py模块可用(只能通过全名constants.power使用)

from constants import power__init__.py模块和power.py模块可用(可以使用短名power来使用)

10.3  查看模块内容

l  dir():dir函数会将对象的所有特性列出

>>> import copy

>>> dir(copy)

['Error', 'PyStringMap', '_EmptyClass', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_dispatch', '_copy_immutable', '_copy_inst', '_copy_with_constructor', '_copy_with_copy_method', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_inst', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', '_test', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

>>> [n for n in dir(copy) if not n.startswith('_')]

['Error', 'PyStringMap', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']

l  通过__all__变量

>>> copy.__all__

['Error', 'copy', 'deepcopy']

如果这样导入模块:from copy import *,那么只能使用__all__变量中的3个函数。编写模块时,设置__all__变量是为了屏蔽掉程序不需要的变量、函数和类。

l  help或者查看文档字符串

>>> help(copy)

>>> help(copy.copy)

>>> copy.__doc__

>>> copy.copy.__doc__

l  阅读官方文档或者源代码

https://www.python.org/doc/

如何查找源代码所在目录:

>>> print copy.__file__

D:\Python27\lib\copy.pyc

11.文件

l  f = open(),f.close()

l  f.read(),f.write()

l  f.readlines(),f.readline(),f.writelines()

>>> f = open(r"E:\学习\Python\file.txt",'w+')

>>> f.write("Hello,world!\n")

>>> f.write("Python\n")

>>> f.close()

>>> f = open(r"E:\学习\Python\file.txt")

>>> f.read(5)

'Hello'

>>> f.read()

',world!\nPython\n'

>>> f.close()

>>> f = open(r"E:\学习\Python\file.txt")

>>> f.readlines()

['Hello,world!\n', 'Python\n']

>>> f.close()

>>> f = open(r"E:\学习\Python\file.txt")

>>> f.readline()

'Hello,world!\n'

>>> f.readline(5)

'Pytho'

>>> f.close()

>>> f = open(r"E:\学习\Python\file.txt",'a+')

>>> f.writelines(['nwpu\n','zhangleilei\n'])

>>> f.close()

>>> f = open(r"E:\学习\Python\file.txt")

>>> f.readlines()

['Hello,world!\n', 'Python\n', 'nwpu\n', 'zhangleilei\n']

l  文件对象是可迭代的,可以在for循环中直接使用

>>> import string

>>> from string import maketrans

>>> table = maketrans(string.lowercase,string.uppercase)

>>> f = open(r"E:\学习\Python\file.txt")

>>> for line in f:

line.translate(table)

 

 

'HELLO,WORLD!\n'

'PYTHON\n'

'NWPU\n'

'ZHANGLEILEI\n'

>>> f.close()

>>> f = open(r"E:\学习\Python\file.txt")

>>> list(f)   #达到的效果和readlines()相同。

['Hello,world!\n', 'Python\n', 'nwpu\n', 'zhangleilei\n']

>>> f.close()

l  为了确保文件能关闭,可以使用with语句:

>>> with open(r'E:\学习\Python\file.txt') as f:

f.readlines()

 

 

['Hello,world!\n', 'Python\n', 'nwpu\n', 'zhangleilei\n']

>>> f.read()

 

Traceback (most recent call last):

  File "<pyshell#3>", line 1, in <module>

    f.read()

ValueError: I/O operation on closed file

with语句可以打开文件并且将其赋值到变量上(本例为f),然后就可以对文件进行操作。文件在语句结束后自动关闭,即使是由于异常引起的结束也是如此。

笔记pdf下载:http://pan.baidu.com/s/1hqzL1gK

PyQt4快速入门:http://pan.baidu.com/s/1hqzf8wc

posted @ 2014-07-21 15:22  Andy Cheung  阅读(374)  评论(0编辑  收藏  举报