python 进阶

循环设计:

  1. 循环对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    >>> f = open('test.txt')
    >>> f.next()
    '123\n'
    >>> f.next()
    '456\n'
    >>> f.next()
    '789\n'
    >>> f.next()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration
  2. 迭代器:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    >>> a = [1,2,3]
    >>> b = iter(a)
    >>> b.next()
    1
    >>> b.next()
    2
    >>> b.next()
    3
    >>> b.next()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration
  3. 生成器:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    >>> def gen():
    ... a = 10
    ... yield a
    ... a = a*10
    ... yield a
    ... yield 1000
    ...
    >>> for i in gen():
    ... print i
    ...
    10
    100
    1000
  4. 生成器表达式:

    1
    2
    3
    >>> L = [ x**2 for x in range(3)]
    >>> L
    [0, 1, 4]
  5. 表推导

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    >>> G = ( x**2 for x in range(3) )
    >>> G
    <generator object <genexpr> at 0x7feb3b6fd2d0>
    >>> G.next()
    0
    >>> G.next()
    1
    >>> G.next()
    4
    >>> G.next()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    StopIteration

动态类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1.动态类型
* 引用
* 引用与对象分离

2. 传值(值传递)
>>> a = 1
>>> def change_i(a):
... a = a+1
... pass
... return a
...
>>> print(change_i(a))
2
>>> print(a)
1

3. 传址(指针传递)
>>> b = [1,2,3]
>>> def change_l(b):
... b[0] = b[0] + 1
... return b
...
>>> print(change_l(b))
[2, 2, 3]
>>> print(b)
[2, 2, 3]

常见函数OOP

1
2
3
4
5
6
hasattr(o,f)
getattr(o,f)
setattr(o,f,new_f)
delattr(o,f)
isinstance(o,f)
issubclass(c,par)

数据库

1
2
3
4
5
6
7
8
9
1. 连接数据库
2. 创建数据库
3. 创建表
4. 插入数据
5. 查询数据
6. 更新数据
7. 删除数据
8. 提交数据
9. 关闭数据库