---
title: "Python学习笔记"
author: "mrjeye"
date: "2011-05-19T10:17:54Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2011-05-19T10:17:54Z"
id: 1049915
url: "https://mrjeye.iteye.com/blog/1049915"
---

python，怎么说呢，感觉很好玩，以下说明几点笔者感兴趣的东西：
    它抛弃了包裹代码块的花括号，而只依据缩进对代码块进行理解（语句有代码块的要以：结束）
    注释用#，若一行以#开头，则不会被解释
    
    FOR循环的用法不同，Python的FOR和java中的for in功能一样,具体可以参照后续代码
    for语法：
    for iter in iter:
    ...
    else:    #当且仅当在FOR循环结束时没遇到BREAK标签时执行
    ...

    对象的比较有些时髦：
    >>> 2>1<3
    True        #相当于：(2>1) and (1<3)
    >>> 2>1<0
    False
    
    这是一条正确的赋值方法：i=j=1    #i=1;j=1
    
    列表：x=        #值可变，EG：x=4
    元组：x=(1,2,3)        #值不可变
    字典：dict={'name':'tom','age':18}    #可改值，EG：dict=20
        迭代：首先调用 dict.keys() 得到‘键’，然后用for in依次取值 
        EG:
            >>>dict={1:1,2:2}    #其键与值理论上来说允许为任何对象
            >>>keys = dict.keys()
            >>>for k in keys:
            ...    print('key is :%s,value is :%s' % (k,dict))

    字符串倒有些没见过的语法
    >>> str='this is a test .'    #声明一个对象（字符串，字符串两边可用单引或双引号）
    >>> str            #返回（会直接打印）STR中从第5个索引位到最后的子字符串（索引从0开始，最后一个位置索引为-1，不含最后一个位置的值）
    'is a test '            
    >>> str            #返回字符串从开始位置到第4个索引位置的子字符串
    'this'
    >>> str*2            #重复两次字符串（传说+、-、*、/等运算符可用于很多对象）
    'this is a test .this is a test .'
    >>> str            #取第6个索引位置的字符
    's'

    原始字符串：引号前加 r 标识的字符串为一个原始字符串，其不对\转义

    声明字符串时可用三引号，用以允许一个字符串跨多行的情况
    >>> responseTxt = '''<html>
    ...     <head>
    ...             <title>test</title>
    ...     </head>
    ...     <body>
    ...             Hello
    ...     </body>
    ... </html>'''
    >>> print responseTxt
    <html>
        <head>
            <title>test</title>
        </head>
        <body>
            Hello
        </body>
    </html>
    >>> responseTxt
    '\n<html>\n\t<head>\n\t\t<title>test</title>\n\t</head>\n\t<body>\n\t\tHello\n\t
    </body>\n</html>'

    可以这样声明一个字符串:s='Hello'' ''Python'
    >>> 'Hello'' ''Python'
    'Hello Python'

    #string.capitalize()    把字符串第一个字符转换成大写

    #string.center(len)    将string居中，两头用空格填充
    >>> 'abc'.center(16)
    '      abc       '

    #string.count(str])    #返回str在string中出现的次数
    >>> s='abcdada'
    >>> s.count('a')
    3
    
    >>> s='abcdada'
    >>> s.zfill(10)
    '000abcdada'

    迭代字符串中的字符用enumerate
    >>> for idx,ch in enumerate('abc'):    #可以理解成函数enumerate返回一个元组
    ...     print('idx :%d,ch :%s' %(idx,ch))
    ...
    idx :0,ch :a
    idx :1,ch :b
    idx :2,ch :c
    
    #元组类型的参数转换
    >>> dict = {'a':'1','b':'2'}
    >>> print 'The %(a)r and %(b)s' %dict
    The '1' and 2
    
    #字符串之Template
    >>> from string import Template
    >>> t = Template('the value of key \'id\' is ${id}')
    >>> t.substitute(id=5)
    "the value of key 'id' is 5"

    变量名不能以$开始、不推荐使用__作为变量的开始
    列表解析是个好玩意（可能只是好奇吧- -;），可以筛选出一些元组
    
    OO时：
    构造方法名字特别: 
        >>>def __init__(self):
        ...    ...
    在类中的所有需要供外部访问的方法第一个参数都是指向调用者的 self 引用
        ...
        >>>def add(self,i,j):
        ...    return i+j
    关于OO，据说不是PYTHON的重点（至少笔者看的这本书上讲得不多），但本人非常喜欢


    关于运行代码：
        你可以打开python的IDLE或使用python命令（WINDOWS下）打开它的控制台
        然后直接输入命令交互执行，或这样：python c:\Python26\cat.py 指定一个PY文件
        其它系统笔者还没了解过，以后会接触到
        （关于什么安装配置，这里就不说了）

    导入模块，import module_name、from moudle_name import Object

===================================================================================
简单的入门知识

玩玩FOR语句
>>> def jfor(begin,end,step):
...     flag = 0
...     for i in range(end-begin+1):
...             if flag ==0:
...                     print i+begin
...                     flag=step-1
...             else:
...                     flag-=1
...

FOR 中的 enumerate
>>> for i,ch in enumerate('abc'):
...     print '%d is %s' %(i,ch)
...

列表解析--筛选
>>> r = 
>>> r


文件操作
1---

>>> def f():
...     fileName = raw_input('Type file name :')
...     for eachLine in file(fileName,'r'):    #模式可选read/write/append...
...             print eachLine,
...
>>> f()
Type file name :c:\1.log
this is a test .
haha

2---

>>> def f():
...     fileName = raw_input('Type file name :')
...     try:
...             for eachLine in file(fileName,'r'):
...                     print eachLine,
...     except IOError,e:
...             print 'open/read file error :%s' %(e)
...
>>> f()
Type file name :c:\nofile
open/read file error : No such file or directory: 'c:\\nofile'
>>> f()
Type file name :c:\1.log
this is a test .
haha

OO
class Cat(object):
    name=''        #stact property
    def __init__(self,name):
        print "init the cat (%s)." %(name)
        self.__class__.__name__=name
    def setName(self,name):
        self.__class__.__name__=name
    def getName(self):
        return self.__class__.__name__

此猫的实例对NAME都引用同一个地址

再来一个Cat
class Cat(object):
    __name = ''    #private property
    __age =0
    def __init__(self,name,age):
        self.__name = name
        self.__age = age
        print 'init cat , name is %s;age is %d' %(name,age)
    def getName(self):
        return self.__name
    def getAge(self):
        return self.__age
    def setName(self,name):
        self.__name = name
    def setAge(self,age):
        self.__age = age

此猫的实例对NAME、AGE的引用是私有的
（没有看到OO那去，这只是猜想，如果有问题，请赐教- -;）
-----------------------------------------------------------
用OO来个实例
模拟DOS界面操作，启动程序用户选择相应功能操作:

class Main(object):
    'the main class .'
    def __init__(self):
        self.showMenu()        #go to main menu
    def showMenu(self):
        selectItem = int(raw_input('Select the function (1-add two num ; 2--say some worlds ; 0--exit):'));
        while(selectItem!=0):        #loop until user type '0'
            if selectItem == 1:
                no = NumOper()    #just play
                first = int(raw_input('Type the first number :'))
                secrend = int(raw_input('Type the secrend number :'))
                print '%d+%d=%d' %(first,secrend,no.add(first,secrend))
                del no
            elif selectItem == 2:
                str = raw_input("Type yout name :");
                print 'Hello %s , Welcome to back !' %(str)
            else:
                print 'you choose item (%d) is invalid .' %(selectItem)
            selectItem = int(raw_input('Select the function (1-add two num ; 2--say some worlds ; 0--exit):'));
        print 'bye ~~'
        exit()
#just play
class NumOper(object):
    'the number oper .'
    def add(self,fir,sec):
        return fir+sec


对象的属性可以这样访问：
>>> import cat
>>> c=cat.Cat('cat',18)
init cat , name is cat;age is 18
>>> c
<cat.Cat object at 0x00BA3810>
>>> id(c)
12204048
>>> dir(c)

>>> c._Cat__age    #访问属性
18
===================================================================================
第三章节那些东西

变量
在python中，不用显示地声明变量，也不用给变量指定类型，一切的事都将在变量第一次被赋值是自动声明

赋值语句可以这样：i,j,k=(1,2,3)    #当然可以不要括号
交换变量的值：x,y=y,x
    甚至可以这样做:x,y,z=y,z,x

如果模块是导入的，在里面 __name__ 会被设置成模块的名字；否则如果模块是直接执行的 __name__ 会被设置成 __main__
这样的话，可以在每一个模块写入相应的测试代码，在测试代码入口（顶层代码）判断是否是直接执行的，若是则执行相应测试代码；反之不管

经典的异常语句
try:
    ...
except IOError,e:    #估计python会把错误信息放在变量e里面
    ...
else:
    ...        #这里执行的条件是：TRY块没有发生异常

关于os模块
    判断一个文件是否存在: os.path.exists(__file)
    得到当前系统的分行符：os.linesep

字符串函数
    >>> s='abc'+'''
    ...
    ... '''
    >>> s
    'abc\n\n'
    >>> s.strip()
    'abc'