ActivePython2.6-Document(tutorial)-阅览笔记

ActivePython2.6-Document(tutorial)--阅读笔记

ActivePython2.6-Documentation--阅读笔记

    0,python tutorial
    --Python 2.6 for windows 软件包中自动文档中的教程。

 

由  王宇 原创并发布

        1、阅读python文档,笔记:

            1、调用python的解析器,在命令行中直接执行:python

            2、在计算器中,使用pyton


                (1)在提示符中输入,自动多行输入,回车空行结束多行输入

                (2)Numbers:3

                (3)Strings:HELLO="Hello,world!!"printHELLO

                (4)unicodeStrings:u'Helloworld"

                (5)Listsa=['spam','eggs',100,1234]

                    >>>a[0]

                    'spam'

            3、控制语句:

                3.1 if elif else    

                    >>>ifx<0:

                    ...    x=0

                    ...    print'Negative'

                    ...elsex==0:

                        print'Zero'

                3.2 for


                    >>>a=['cat','window','dog']

                    >>>forxina:

                    ...    printx,len(x)

                    cat3

                    window6

                    dog3

                3.3 range()

                    >>>range(5)

                    [5,6,7,9,10]

                    >>>range(5,9)

                    [5,6,7,8]

                    >>>range(5,10,2)

                    [5,7,9]

                3.4 break,continue

                3.5 pass

                3.6 def

                    MoreonDefiningFunctions

                        DefaultArgumentValues

                    >>>deffib(n):

                    ...    b=10

                    ...    whileb<n:

                    ...        b=b+1

                    ...

                    >>>fib(20)

                注意缩进问题

            4、数据结构

                4.1 More on list    

                >>>a=[66,25,333,333,1,1234.5]

                    list.append()

                        >>>a.append(333)

                        >>>a

                            [66,25,333,333,1,1234.5,333]

                    list.extend()

                    list.insert()

                    list.remove()

                    list.pop()

                    list.index()

                    list.count()

                    list.sort()

                    list.reverse()

                    UsingListsasStacks

                        >>>stack=[3,4,5]

                        >>>stack.pop

                            5

                    UsingListasQueues

                        >>>fromcollectionsimportdeque

                        >>>queue=deque(["Eric","John","Michael"])

                        >>>queue.append("Terry")

                        >>>queue.popleft()

                        'Eric'

                        >>>queue

                        deque(["John","Michael","Terry"])

                    FunctionalProgrammingTools

                        filter()

                        map()

                        reduce()

                    ListComprehensions   

                    NestedListComprehensions

                4.2 The delstatement

                    >>>a=[-1,1,66.25,333,333,1234.5]

                    >>>dela[0]

                    >>>a

                        [1,66.25,333,333,1234.5]

                    >>>dela[2:4]

                    >>>a

                        [1,66.25,1234.5]

                    >>>dela[:]

                    >>>a

                    []

                4.3 Tuple sand Sequences

                4.4 Sets

                    >>>basket=['apple','orange','apple','pear']

                    >>>fruit=set(basket)

                    >>>fruit

                    set(['apple','orange','apple','pear'])

                    >>>'organge'infruit

                    True

               

                4.5 Dictionaries

                    >>>tel={'jack':4098,'sape':4139}

                    >>>tel['guido']=4127

                    >>>tel

                    {'jack':4098,'sape':4139,'guido',4127}

                    >>>tel['jack']

                    4098

                4.6 Looping Techniques

                    >>>tel={'jack':4098,'sape':4139}

                    >>>fork,vintel.iteritems():

                    ...    printk,v

                    ...

                        'jack'4098

                        'sape'4139

                4.7 More on Conditions

                    >>>a,b,c=1,2,3

                    >>>a<b==c

                    Flase

                    >>>c=2

                    >>>a<b==c

                    True

                4.8 Comparing Sequences and Other Types   

                       

            5、模块

                5.1 Modules:currentdirectionfile:fibo.py;importfibo;fibo.fib(100)


                5.2 More on Modules


                    >>>fromfiboimportfib,fib2

                    >>>fromfiboimport*

                    >>>fib(500)

                    5.2.1Excutingmodulesasscripts

                        pythonfibo.py<arguments>

                        addingthiscodeattheendofyourmodule.

                            if__name__=="__main__":

                                importsys

                                fib(int(sys.argv[1]))

                        $pythonfibo.py50

                    5.2.2TheModuleSearchPath

                        PYTHONPATH

                        sys.path

                    5.2.3CompiledPythonfiles

                5.3 Standard Modules:PythonLibraryReference**

                    winregmoduleisonlyprovidedonWindowssystem.

                    IfPYTHONPATHisnotset,youwillmodifysys.path

                        >>>importsys

                        >>>sys.path.append('/usr/phthon');

                5.4 **Thedir()Function

                5.5 Package:PackageisPhthon'snamespaceofmodules

                    importsound.effects.echo

                    fromsound.effectsimportecho   

                    5.5.1Importing*FromaPackage

                        __all__

                    5.5.2Intra-packageReferences

                    5.5.3PackageinMultipleDirectories

            6、输入和输出

                6.1 Fancie rOutput Formatting

                    str():human-readable

                    repr():Itcanbereadbytheinterpreter

                    6.1.1

                    6.1.2Oldstringformatting

                        >>>print'Thevalueis%5.3f'%math.pi

                        >>>Thevalueis3.142

                6.2 Reading and Writing Files

                    f=open('/tmp/dinw.txt','w')

                    secondparametercontain'o''r''w'...

                    6.2.1MethodsofFileObjects

                        f.read()

                        f.readline()

                        f.readlines()

                        f.write()

                        f.tell()

                        f.seek()

                        f.close()

                    6.2.2ThepickleModel???   

                   

            7、错误和异常

                Syntaxerrors

                Exceptions

                HandingExceptions

                    try:

                    exceptValueerror:

                RaisingExceptions

            8、类:Noconstructoranddestructor

                8.1 A Word About Terninology

                8.2 Python Scopes and Name Spaces(???)

                8.3 A First Look at Classes


                    8.3.1ClassDefinitionSyntax

                        classClassName:

                            <statement-1>

                            ..

                            ..

                            <statement-N>

                    8.3.2ClassObjects

                        classMyClass:

                            """Asimpleexampleclass"""

                            i=12345

                            deff(self):

                                return'helloworld'

                       

                        attribute:

                            >>>MyClass.i

                            12345

                            >>>MyClass.f

                       

                        instantiation:

                            x=MyClass()

                            initialstate:__init__()

                                classComplex:

                                    def__init__(self,realpart,imagpart):

                                        self.data=[]

                                        self.r=realpart//私有的,类实例化得特性表现

                                        self.m=imagpart

                            >>>x=Complex(3.0,-4.5)

                            >>>x.r,x.i

                            (3.0,-4.5)

                    8.3.3InstanceObjects

                        x.fisnotthesamethingasMyClass.f--itisamethodobject,notafunctionobject.   

                    8.3.4MethodObject(???)

                        >>>classMyClass:

                        ...    x=1

                        ...

                        >>>obj1=MyClass()

                        >>>obj1.x

                        1

                        >>>obj2=MyClass()

                        >>>obj2.x

                        1

                        >>>obj1.x=2

                        >>>obj2.x

                        2//怎么会是2,而不是1?这个地方把我给搞晕了,颠覆了我对类实例化的概念,如何实现类似C++的类实例化?

                        >>>MyClass.x//整个是一个全局静态变量!!

                        2

                8.4 Random Remarks

                    deff1(self,x,y):

                        returnmin(x,x+y)

                   

                    classC:

                        f=f1

                        defg(self):

                            return'hellowworld'

                        h=g

                Nowf,gandhareallattributesofC   

                8.5 Inheritance    (继承)

                    classDerivedClassName(BaseClassName):

                        <statement-1>

                        ...

                        ...

                        <Statement-N>

                    8.5.1MultipleInheritance

                    classDerivedClassName(Base1,Base2,Base3):

                        <statement-1>

                        ...

                        ...

                        <Statement-N>

                    按照顺序寻找方法。   

                8.6 Private Variables

                    定义变量前加:'_'

                8.7 Odds and Ends


                    classEmployee:

                        pass

                    john=Employee()

                    #Fillthefieldsoftherecord(太随意了,很容易犯错误!)

                    john.name='JohnDoe'

                    john.salary=1000

                8.8 Exceptions Are Classes Too

                8.9 Iterators


                    forelementin[1,2,3]:

                        printelement

                    forelementin(1,2,3):

                        printelement

                    forkeyin{'one':1,'two':2}:

                    printkey

                    forcharin"123":

                    printchar

                    forlineinopen("myfile.txt"):

                    printline

                    ------------------------               

                    >>>s='abc'

                    >>>it=iter(s)

                    >>>it

                    <iteratorobjectat0x00A1DB50>

                    >>>it.next()

                    'a'

                    >>>it.next()

                    'b'

                    >>>it.next()

                    'c'

                    >>>it.next()

                   

                    Traceback(mostrecentcalllast):

                    File"<stdin>",line1,in?

                    it.next()

                    StopIteration

                    ------------------------

                    classReverse:

                    "Iteratorforloopingoverasequencebackwards"

                    def__init__(self,data):

                    self.data=data

                    self.index=len(data)

                    def__iter__(self)://returnanobjectwithanext()

                    returnself

                    defnext(self):

                    ifself.index==0:

                    raiseStopIteration

                    self.index=self.index-1

                    returnself.data[self.index]

                   

                    >>>forcharinReverse('spam')://循环执行,每次递减1,类的处理太别扭了,就是一个全局封装,无实例化得概念

                    ...printchar

                    ...

                    m

                    a

                    p

                    s

                8.10 Generators       

                    defreverse(data):

                    forindexinrange(len(data)-1,-1,-1):

                    yielddata[index]

                   

                    >>>forcharinreverse('golf'):

                    ...printchar

                    ...

                    f

                    l

                    o

                    g

                8.11GeneratorExpressions

            9.BriefTouroftheStandardLibrary   


                9.1 Operating System Interface

                    >>>importos

                    >>>dir(os)

                    <returnsalistofallmodulefunctions>

                    >>>help(os)//**查看到os得详细内容,很有用。:q退出

                    <returnsanextensivemanualpagecreatedfromthemodule'sdocstrings>

                9.2 File Wildcards

                    >>>importglob

                    >>>glob.glob('*.py')

                    ['primes.py','random.py','quote.py']

               

                9.3 Command Line Arguments

                    >>>importsys

                    >>>printsys.argv

                    ['demo.py','one','two','three']

           

                9.4 Error Output Redirection and Program Termination

                    >>>sys.stderr.write('Warning,logfilenotfoundstartinganewone\n')

                    Warning,logfilenotfoundstartinganewone

                9.5 String Pattern Matching

                    Theremoduleprovidesregularexpressiontoolsforadvancedstringprocessing

                    >>>importre

                    >>>re.findall(r'\bf[a-z]*','whichfootorhandfellfastest')

                    ['foot','fell','fastest']

                    >>>re.sub(r'(\b[a-z]+)\1',r'\1','catinthethehat')

                    'catinthehat'

                    ----------

                    >>>'teafortoo'.replace('too','two')

                    'teafortwo'

                9.6 Mathematics

                   

                    ThemathmodulegivesaccesstotheunderlyingClibraryfunctionsforfloatingpointmath:

                    Therandommoduleprovidestoolsformakingrandomselections

                9.7 InternetAccess

                    urllib2、smtplib

                    >>>importurllib2

                    >>>forlineinurllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):

                    ...if'EST'inlineor'EDT'inline:#lookforEasternTime

                    ...printline

                   

                    <BR>Nov.25,09:43:32PMEST

                   

                    >>>importsmtplib

                    >>>server=smtplib.SMTP('localhost')

                    >>>server.sendmail('soothsayer@example.org','jcaesar@example.org',

                    ..."""To:jcaesar@example.org

                    ...From:soothsayer@example.org

                    ...

                    ...BewaretheIdesofMarch.

                    ...""")

                    >>>server.quit()

                   

                9.8 Dates and Times

                    datatimemodule

                9.9 Data Compression

                    zlib,gzip,bz2,zipfileandtarfile.

                9.10 Performance Measurement

                    >>>fromtimeitimportTimer

                    >>>Timer('t=a;a=b;b=t','a=1;b=2').timeit()

                    0.57535828626024577

                    >>>Timer('a,b=b,a','a=1;b=2').timeit()

                    0.54962537085770791

                   

                9.11 Quality Control

                    doctest:

                        defaverage(values):

                        """Computesthearithmeticmeanofalistofnumbers.

                       

                        >>>printaverage([20,30,70])

                        40.0

                        """

                        returnsum(values,0.0)/len(values)

                       

                        importdoctest

                        doctest.testmod()#automaticallyvalidatetheembeddedtests

                   

                       

                    unittest:

                        importunittest

                       

                        classTestStatisticalFunctions(unittest.TestCase):

                       

                        deftest_average(self):

                        self.assertEqual(average([20,30,70]),40.0)

                        self.assertEqual(round(average([1,5,7]),1),4.3)

                        self.assertRaises(ZeroDivisionError,average,[])

                        self.assertRaises(TypeError,average,20,30,70)

                       

                        unittest.main()#Callingfromthecommandlineinvokesalltests

                   

                9.12BatteriesIncluded    :

                    通过获得更大的包,来应对复杂的应用。

           

            10.BriefTouroftheStandardLibrary-PartII

                10.1 Output Formatting

                    repr//

                    pprint//打印输出的格式

                    textwrap//设定换行的大小

                    locale

                10.2Templating

                10.3 Working with Binary Data Record Layouts