Python学习笔记

Python相关文档
0.1. Python标准文档
0.2. Python实用大全
0.3. 迷人的Python
0.4. 深入理解Python
0.5. Python扩展库网址 http://pypi.python.org/
     Python官方网址 http://www.python.org/

1. if,python中没有switch语句
    if(a+1==b):
        print("if");
    elif(a+1>b):
        print("elif");
    else:
        print("else");

2.while语句有else部分,while/for语句中出现break时,else不执行
    running=True;
    while(running):
        if(i>10):
            running=False;
        print(i);
        i+=1;
    else:
        print("end while");

3.Boolean的值有 True 和 False

4.for ..in 语句,range(start,end,step)
    for i in range(0,10):
        print (i);
    else:
        print("end for");

5.continue和,break语句从for或while循环中结束,循环的else块将不执行

6.标准输入
    s=input("Enter a string:");
    6.1.格式化字符串
        a=10
        b='string'
        c='a:%d,b:%s'%(a,b)

7.函数 有关键字def定义
    #define function say()
    def say():
        print("function say()");
    #call the function
    say();

    7.1.函数形参
        #define function say(a,b)
        def say(a,b):
            print("function say()",a,b);
        #call the function
        say(a,b);

    7.2.默认参数值
        #define function say(a,b)
        def say(a,b=0):
            print("function say()",a,b);


        #call the function
        say(a,b);
        say(a)

    7.3.关键参数 指定其中一部分参数
        #define function say(a,b,c,d)
        def say(a,b=0,c=1,d=2):
            print("function say()",a,b,c,d);


        #call the function
        say(a,c=100);
        say(a,b=2,d=3)

    7.4.return语句
        def max(a,b):
            if(a>b):
                return a;
            else:
                return b;

        #call
        print max(a,b);

    7.5.元组,列表,字典作为函数的参数
        元组或列表
        def powersum(power, *args):
            total=0
            for i in args:
                total+=pow(i,power)
            return total

        print (powersum(2,3,4))
        print (powersum(2,10))

8.全局变量与局部变量
    def func():
        global x;
        print ("x is",x);
        x=100;
    #call the func()
    x=200;
    func();
    print (x);

9.DocStrings文档字符串
    def docs():
        '''this is a description of
        function docs()'''
        print ("docs()");

    print (docs.__doc__);

10.命令行参数
    import sys;

    #sys.argv[0] 为命令本身,for语句从sys.argv[0]开始
    #sys.argv为命令行参数列表
    for i in sys.argv:
        print (i);

11.模块
  11.1.模块的__name__
  if (__name__=='__main__'):
      print ("main");
  else:
      print ("be imported from another module");

  11.2.模块的创建
    #!user/bin/python
    #filename:mymodule.py

    if (__name__=='__main__'):
        print ('my module main');
    else:
        print ('my module is imported');

    def func():
        print ('my module func()');
    version='0.0.1';

    #import in another py file
    import mymodule;
    mymodule.func();
    print (mymodule.version)

    #or
    from mymodule import func,version;
    func();
    print ('Version:',version);

  11.3.模块函数dir() 列出此模块中定义的函数,类和变量
    import sys
    for i in dir(sys):
        print (i)

12.数据结构 列表list, 通过中括号中逗号分隔的item定义
    yourlist=['y1','y2','y3','y4','y5']
    mylist=list();
    mylist.append('1');
    mylist.append('2');
    mylist.append('3');
    mylist.append('4');

    mylist.insert(mylist.count('1'),'5')
    mylist.extend('6');
    print (mylist.index('5'))
    print (mylist[1])
    #mylist.reverse();
    #mylist.sort(key=None, reverse=True)
    for i in mylist:
        print (i)

    12.1.序列 - 代表倒数第几个index
        #all items in list
        mylist[0:-1]
        mylist[:]
        mylist[0:]

        #除最后一个的所有序列
        mylist[:-1]

13.数据结构 元组tuple,和字符串一样值不可变,通过圆括号中用逗号分隔的项目定义
    mytuple=('1','2','3','4','5','4')

    print (mytuple.count('4'))
    print (mytuple.index('5'))
    print (mytuple[1])
    for i in mytuple:
        print (i)

14.数据结构 字典dict, 类似于map,键值对在字典中的标记方式
    d={ key1 : value1,
       key2 : value2,
       key2 : value3,
       key2 : value4
    } 键/值对用 : 分隔,各个对用 , 分隔 所有这些都包含在花括号里面
    d = {
    'w1' : 'w1@xx.com',
    'w2' : 'w2@xx.com',
    'w3' : 'w3@xx.com',
    'w4' : 'w4@xx.com',
    'w5' : 'w5@xx.com' }

    #add an item
    d['w6'] = 'w6@yy.cn'

    #delete an item
    del d['w3']

    #access an item
    print (d['w4'])

    #key and values
    for i, j in d.items():
        print (i, ':', j)
    #values
    print (d.copy().values())

15.class类 如下的代码中__init__()为构造函数, self为this指针, __del__()为析构函数
  Python不会自动调用基本类的constructor(__init__())和destructor(__del__()),你得亲自专门调用它。

    class per:
        age=0
        def __init__(self, name):
            self.name=name
            print ("init name:%s"%self.name)
        def say(self):
            print ("per::say()")
        def set(self,age):
            self.age=age
        def get(self):
            return self.age
        def __del__(self):
            self.age=0
            print ("__del__()%d"%self.age)

    person=per('person')
    person.say()
    person.set(100)
    print (person.get())

15.1.类的继承 class subclass(baseclass1,baseclass2,...,baseclassn)
    class base:
        name=''
        age=0
        def __init__(self,name,age):
            self.name=name
            self.age=age
            print ('base::__init__():name:%s,age:%d' \
                    %(self.name,self.age))
        def tell(self):
            print ('base::name:%s,age:%d'%(self.name,self.age))
        def __del__(self):
            self.name=''
            self.age=0
            print ('base::__del__()')

    class suba(base):
        sex=''
        def __init__(self,name,age,sex='man'):
            self.sex=sex
            base.__init__(self,name,age)
            print ('suba::__init__():name:%sage:%dsex:%s' \
                    %(self.name,self.age,self.sex))
        def __del__(self):
            base.__del__(self)
            print ('suba::__del__()')


    a=suba('wangyf',25,'man')
    a.tell()

16.异常处理 try...except
    import sys

    try:
        s=input('Enter ctrl+c to test EOFError:')
        Print ('Print is not defined')
    except EOFError:
        print ('EOF is Entered')
    except Exception:
        print ('default Exception')
    else:
        print ('no Exception happened')

16.1.引发异常 raise 相当于在可能异常的地方调用异常类,相当于throw
  可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类

    class InputException(Exception):
        def __init__(self,x):
            self.x=x
            print ('InputException::__init__():x:[%d]'%self.x)
        def __del__(self):
            print ('InputException::__del__()')
    try:
        s=input('Enter some word:')
        if(len(s) < 5):
            print ('string len is:%d'%(len(s)))
            #throw a exception
            raise InputException(len(s))
    except EOFError:
        print ('EOF is Entered')
    except Exception:
    #上面的异常此处也会捕获到
        print ('except')
    else:
        print ('else')

16.2.try...finally异常处理
    无论异常发生与否的情况下,finally范围里的语句都会被执行
    try:
        s=input('Enter string:')
    finally:
        print ('str s is:%s'%s)

17.exec和eval执行引号里面的语句
    exec ('print ('this is exec command')')
    eval ('print ('this is eval command')')

18.lambda形式
    lambda语句被用来创建新的函数对象,并且在运行时返回它们。
    def repeater(n):
        return lambda s:s*n

    three=repeater(3)
    print (three('main')

19. others
  19.1. 引号'"在python中没有区别。即 '' == "", \''' ''' == \""" """指示多行的字符串。
  19.2. python中的标识符与c语言一样。
  19.3. pass语句在Python中表示一个空的语句块。
  19.4. from sys import * == import sys :即在模块sys中导入子模块。

20. python调用c的库文件文件
    20.1. c函数编译成动态库文件
    /* test.cpp */
    #include <stdio.h>

    extern "C" {
        void display() {
            printf("This is Display Function\n");
        }
    }
    编译成动态库文件。
    g++ test.cpp -fPIC -shared -o libtest.so

    20.1. python调用
    import ctypes
    so = ctypes.CDLL("./libtest.so")
    so.display()

21. python连接oracle数据库
  使用库文件cx_Oracle-5.1.tar.gz
  Python扩展库网址 http://pypi.python.org/获取库文件
  编译方式
  python setup.py build
  python setup.py install

    #! /export/home/wangyf/tools/python2.7.2/bin/python
    #coding=UTF-8

    import cx_Oracle

    def hello():
        '''Hello cx_Oracle示例:

        1)打印数据库版本信息.
        2)查询表数据.'''

        conn = cx_Oracle.connect("obs61","obs61","tx8i.hp")
        cur = conn.cursor()
        try:
            print "Oracle Version:%s" % conn.version
            print "Table SUB_POLICY rows:"
            cur.execute('select * from wlan_future_event')
            for row in cur:
                print row
        finally:
            cur.close()
            conn.close()

    hello()

22. python连接mysql数据库
  使用库文件MySQLdb MySQL-python-1.2.3.tar.gz
  Python扩展库网址 http://pypi.python.org/获取库文件
  基本的使用如上,还是很简单的,进一步使用还没操作,先从网上找点资料放上来,以备后续查看

    # -*- coding: utf-8 -*-
    #mysqldb
    import time, MySQLdb

    #连接
    conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")
    cursor = conn.cursor()

    #写入
    sql = "insert into user(name,created) values(%s,%s)"
    param = ("aaa",int(time.time()))
    n = cursor.execute(sql,param)
    print n

    #更新
    sql = "update user set name=%s where id=3"
    param = ("bbb")
    n = cursor.execute(sql,param)
    print n

    #查询
    n = cursor.execute("select * from user")
    for row in cursor.fetchall():
    for r in row:
        print r

    #删除
    sql = "delete from user where name=%s"
    param =("aaa")
    n = cursor.execute(sql,param)
    print n
    cursor.close()

    #关闭
    conn.close()

    22.1.引入MySQLdb库
    import MySQLdb

    22.2.和数据库建立连接
     conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")
     提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象.

    比较常用的参数包括
     host:数据库主机名.默认是用本地主机.
     user:数据库登陆名.默认是当前用户.
     passwd:数据库登陆的秘密.默认为空.
     db:要使用的数据库名.没有默认值.
     port:MySQL服务使用的TCP端口.默认是3306.
     charset:数据库编码.

    更多关于参数的信息可以查这里
     http://mysql-python.sourceforge.net/MySQLdb.html

    然后,这个连接对象也提供了对事务操作的支持,标准的方法
     commit() 提交
     rollback() 回滚

    22.3.执行sql语句和接收返回值
     cursor=conn.cursor()
     n=cursor.execute(sql,param)
     首先,我们用使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.这些方法包括两大类:1.执行命令,2.接收返回值

    cursor用来执行命令的方法:
     callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
     execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
     executemany(self, query, args):执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
     nextset(self):移动到下一个结果集

    cursor用来接收返回值的方法:
     fetchall(self):接收全部的返回结果行.
     fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
     fetchone(self):返回一条结果行.
     scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的第一行移动value条.

    下面的代码是一个完整的例子.
     #使用sql语句,这里要接收的参数都用%s占位符.要注意的是,无论你要插入的数据是什么类型,占位符永远都要用%s
     sql="insert into cdinfo values(%s,%s,%s,%s,%s)"
     #param应该为tuple或者list
     param=(title,singer,imgurl,url,alpha)
     #执行,如果成功,n的值为1
     n=cursor.execute(sql,param)

    #再来执行一个查询的操作
     cursor.execute("select * from cdinfo")
     #我们使用了fetchall这个方法.这样,cds里保存的将会是查询返回的全部结果.每条结果都是一个tuple类型的数据,这些tuple组成了一个tuple
     cds=cursor.fetchall()
     #因为是tuple,所以可以这样使用结果集
     print cds[0][3]
     #或者直接显示出来,看看结果集的真实样子
     print cds

    #如果需要批量的插入数据,就这样做
     sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)"
     #每个值的集合为一个tuple,整个参数集组成一个tuple,或者list
     param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2))
     #使用executemany方法来批量的插入数据.这真是一个很酷的方法!
     n=cursor.executemany(sql,param)

23. python连接其他数据库
    23.1. python连接postgreSQL数据库 py-postgresql-1.0.4.tar
    23.2. python连接sybase数据库 python-sybase 0.39
    23.3. python连接sqlite数据库pysqlite 2.6.3
    23.4. python连接mongodb数据库pymongo-2.1.1.tar.gz

24. python调用c封装的python库
    //包含python的头文件
    #include <python2.7/Python.h>
    // 1 c/cpp中的函数
    int my_c_function(const char *arg) {
        int n = system(arg);
        return n;
    }
    // 2 python 包装
    static PyObject * wrap_my_c_fun(PyObject *self, PyObject *args) {
        const char * command;
        int n;
        if (!PyArg_ParseTuple(args, "s", &command))//这句是把python的变量args转换成c的变量command
            return NULL;
        n = my_c_function(command);//调用c的函数
        return Py_BuildValue("i", n);//把c的返回值n转换成python的对象
    }
    // 3 方法列表
    static PyMethodDef MyCppMethods[] = {
        //MyCppFun1是python中注册的函数名,可以注册多个函数被python脚本调用,wrap_my_c_fun是函数指针
        { "MyCppFun1", wrap_my_c_fun, METH_VARARGS, "Execute a shell command." },
        { "MyCppFun2", wrap_my_c_fun, METH_VARARGS, "Execute a shell command 2." },
        { NULL, NULL, 0, NULL }
    };
    // 4 模块初始化方法init后面必须为库名称initMyCppModule编译的库必须命名为MyCppModule.so
    PyMODINIT_FUNC initMyCppModule(void) {
        //初始模块,把MyCppMethods初始到MyCppModule中
        PyObject *m = Py_InitModule("MyCppModule", MyCppMethods);
        if (m == NULL)
            return;
    }

    g++ -shared -fPIC pythonc.cpp -I/export/home/wangyf/tools/python2.7.2/include -o MyCppModule.so

    # -*- coding: utf-8 -*-
    import MyCppModule
    #导入python的模块(也就是c的模块,注意so文件名是MyCppModule
    r = MyCppModule.MyCppFun1("ls -l")
    r = MyCppModule.MyCppFun2("ls -lrt")
    print r
    print "OK"

25. c调用python
    库文件需要放在python的库目录下
    若使用当前目录下的python库函数需要加载把当前目录加载到库目录下
    PyRun_SimpleString("import sys; sys.path.append('.')");
    # pytest.py
    def add(a,b):
        print "in python function add"
        print "a = " + str(a)
        print "b = " + str(b)
        print "ret = " + str(a+b)
        return a + b

    // ccallp.cpp
    #include <stdio.h>
    #include <stdlib.h>
    #include <python2.7/Python.h>

    int main(int argc, char** argv)
     {
         // 初始化Python
         //在使用Python系统前,必须使用Py_Initialize对其
         //进行初始化。它会载入Python的内建模块并添加系统路
         //径到模块搜索路径中。这个函数没有返回值,检查系统
         //是否初始化成功需要使用Py_IsInitialized。

        PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pRetVal;

        Py_Initialize();
         // 检查初始化是否成功
         if ( !Py_IsInitialized() )
        {
             return -1;
         }

        // 载入名为pytest的脚本(注意:不是pytest.py)
        // PyRun_SimpleString("import sys; sys.path.append('.')");
         pName = PyString_FromString("pytest");
         pModule = PyImport_Import(pName);
         if ( !pModule )
         {
             printf("can't find pytest.py");
             getchar();
             return -1;
         }
         pDict = PyModule_GetDict(pModule);
         if ( !pDict )
        {
             return -1;
         }

        // 找出函数名为add的函数
         pFunc = PyDict_GetItemString(pDict, "add");
         if ( !pFunc || !PyCallable_Check(pFunc) )
         {
             printf("can't find function [add]");
             getchar();
             return -1;
         }

        // 参数进栈
         pArgs = PyTuple_New(2);

        // PyObject* Py_BuildValue(char *format, ...)
         // 把C++的变量转换成一个Python对象。当需要从
         // C++传递变量到Python时,就会使用这个函数。此函数
         // 有点类似C的printf,但格式不同。常用的格式有
         // s 表示字符串,
         // i 表示整型变量,
         // f 表示浮点数,
         // O 表示一个Python对象。

        PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3));
        PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));

        // 调用Python函数
        pRetVal = PyObject_CallObject(pFunc, pArgs);
        printf("function return value : %ld\r\n", PyInt_AsLong(pRetVal));

        Py_DECREF(pName);
        Py_DECREF(pArgs);
        Py_DECREF(pModule);
        Py_DECREF(pRetVal);

        // 关闭Python
        Py_Finalize();
        return 0;
    }
    // sunOS下编译需要指定库文件
    g++ ccallp.cpp -I/export/home/wangyf/tools/python2.7.2/include -o ccallp -lpython2.7 -ldl -lrt
    # 结果
    /export/home/wangyf/python/learn>% ccallp
    in python function add
    a = 3
    b = 4
    ret = 7
    function return value : 7

26. python正则表达式
    26.1. 元字符. ^ $ * + ? { [ ] \ | ( )
    ".":表示任意一个字符。
        匹配的扩展名不是 "bat" 的文件名
        .*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$
    "$":表示必须以指定字符结尾。
    "|":左右表达式任意匹配一个。
    "[]":常用来指定一个字符类别,
    所谓字符类别就是你想匹配的一个字符集。
    字符可以单个列出,也可以用“-”号分隔的两个给定字符来表示一个字符区间。
    例如,[abc] 将匹配"a", "b", 或"c"中的任意一个字符;
    也可以用区间[a-c]来表示同一字符集,和前者效果一致。如果你只想匹配小写字母,re写成 [a-z].

    元字符在类别里并不起作用。例如,[akm$]将匹配字符"a", "k", "m", 或 "$" 中的任意一个;"$"通常用作元字符,但在字符类别里,其特性被除去,恢复成普通字符
    "^"字符本身。例如,[^5] 将匹配除 "5" 之外的任意字符。
    "*":指定前一个字符可以被匹配零次或更多次,而不是只有一次。
    "+":表示匹配一或更多次。
        请注意 * 和 + 之间的不同;"*"匹配零或更多次,所以根本就可以不出现,而 "+"要求至少出现一次.
    "?":表示匹配零或一次。
    "{}":重复限定符是 {m,n},其中 m 和 n 是十进制整数。该限定符的意思是至少有 m 个重复,
        至多到 n 个重复。举个例子,a/{1,3}b 将匹配 "a/b","a//b" 和 "a///b"。
        {0,} 等同于 *,{1,} 等同于 +,而{0,1}则与 ?
    \d 匹配任何十进制数;它相当于类 [0-9]。
  \D 匹配任何非数字字符;它相当于类 [^0-9]。
  \s 匹配任何空白字符;它相当于类 [ "t"n"r"f"v]。
  \S 匹配任何非空白字符;它相当于类 [^ "t"n"r"f"v]。
  \w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
  \W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]。
  这样特殊字符都可以包含在一个字符类中。如,["s,.]字符类将匹配任何空白字符或","或"."。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值