python初级学习笔记

在线教程: http://docs.python.org/tut/tut.html


with open("/home/ghost/had.txt", "w") as f: with语句可以在执行语句后自动关闭文件


学习描述符__get__ __set__P84(高级)

学习装饰器

学习select模块中的epoll



import collections 用于双端队列类 deque

import heapq 用于堆函数的导入

import fileinput 用于读取文件类的导入

import sys 用于系统的一些东西导入

import os 用于系统外部的导入

import time 用于导入时间函数

import random 可以导入随机数,但是是伪随机,如果要用真的随机就要用os.urandom

import shelve 可以用于写文件存储,它比较简单,是用key-value方式存放的

import re 正则表达式函数的导入

import MySQLdb mysql数据库导入模块

import socket 导入套接字类

import urllib 获取网站信息的模块

import urllib2 获取网站信息的模块(当需要http验证,cookie,或者自己写扩展的时候)

import SocketServer 是服务器的框架模块,TCPServer,UDPServer

import select select模块含有select类,epoll类,poll类等

import doctest 测试模块用的,P298 测试很有用

import itertools 此模块用c语言编写。是一种高效的迭代器

import contextlib 模块提供了contextmanager(编写自己的with),closing(结束调用 close),

import threading 线程,进程直接用os.fork()


__init__ 相当于c++的构造函数

__del__ 相当与c++的析构函数

父类名.__init__(self,可以有参数) 在子类的构造函数中调用父类的构造函数的方法(旧的用法)

super(当前类名, self).__init__(可以有参数) 在子类的构造函数中调用父类的构造函数的方法(新)

__getitem__(self, key) 获取指定的key键下表的值 如x = s[2]

__setitem__(self, key, value) 设置指定的key键下表的值 如s[2] = x

__delitem__ (self, key) 删除指定的key下的元素 如del s[2]

property(fget, fset, fdel, doc) 设置成函数像变量一样运用

可以单独只用一个,如size = property(fset = setSize) 后面有例子

__setattr__(self, name, value) 用于 对象名.变量名(name)= 值(value

__getattr__(self, name, value) 用于 对象名.变量名(name) 当对象没有此变量名时才被调用


__str__(self) 用于 print 对象名 或者 str(对象名)

__mro__ 使用的,用于查看继承的东西(distinctdict继承了dict

>>> distinctdict.mro()

[<class '__main__.distinctdict'>, <type 'dict'>, <type 'object'>]


迭代器规则在python3.0中有一些变化。在新的规则中,迭代起对象应该实现__next__方法,而不是next(),二新的内建函数next可以用于访问这个方法。换句话说,next(it)等同于3.0之前的it.next()

__iter__(self)

__new__(cls) 用来判断时候新建了该类,继承的时候(__init__更底层的初始化)



所有基础数据库操作都是一样的,如:

>>>conn = 下载下来的数据库模块名.connect(...)

>>>cur = conn.cursor() //获取数据库游标

>>>游标之后就可以进行各种操作

>>>conn.commit()

>>>conn.rollback()

>>>conn.close()


读写文件:

r+”,可以读写文件,不会打开时候不会删除文件内容

w+”,可以读写文件,会打开时候不会删除文件内容

a+”,可以读写文件,不会打开时候不会删除文件内容


>>> f = open("/home/ghost/had.txt", "r") 文件对象可以是迭代器

>>> for line in f: sys.stdin同样也是

print line




在导入自己模块的时候,可能会看到新文件.pyc后缀结尾。他是平台无关的经过处理(编译)的,已经转换成python能够更加有效地处理的文件,如果稍后导入同一个模块,python会导入.pyc后缀文件而不是.py后缀文件。除非.py后缀文件已经改变


sys.path python需要寻找的路径

sys.platform 使用的平台

sys.stdin

sys.stdout

sys.stderr

sys.argv 使用命令来执行python时并带参数,如python hello.py hello world


os.system 用于运行外部程序或命令

os.execv等都可以将控制权转交给别的程序

os模块很多命令shell下有,还有c语言的函数一大堆。所以os模块很有用

>>> os.linesep linux平台下特有的换行符,路径分割符,环境路径分割符

'\n'

>>> os.sep

'/'

>>> os.pathsep

':'


通常会用if __name__ == “__main__” : 来进行模块测试


告诉编译器还可以在哪里找文件,用于导入自己的模块

>>>import sys

>>>sys.path.append(“路径”)

>>>import myModule


变量的命名最好以下划线开头


任何包含yield语句的函数成为生成器。每次产生一个值(使用yield语句),函数就会被冻结:即函数停在那点等待被激活。函数被激活后就从停止的那点开始执行。在我认为,__iter__是用于类的迭代器,那么yield就是应用于函数的迭代器


dir()函数可以看到对象(类,模块等)中的函数变量等


help()函数可以查看到如果运用这个类,对象,模块


python3以前新类定义前加

__metaclass__ = type


python中,如果直接在终端用python,如果有函数等什么有返回的话,会直接在下一行输出,如果没有就没有显示,这样可以很好的知道函数有没有返回,这样有利于python脚本的编写,知道会不会有函数返回,不然很容易以为函数会有返回。(这是一种测试)


>>> class A: 超级注意,属性或方法名前用__可以表示如c++private

__a = 1 但不是绝对访问不到,用对象._类名__变量名 就可以访问了

def getA(self):

return self.__a


try/except(.., .., ..).../else语句中,else只有在没有错时执行

try/except(.., .., ..)...

try/except(.., .., ..).../else/finally finally可以怎么组合都行如,try/finally


>>> a = A()

>>> a.getA()

1

>>> a._A__a

1


可以生成一个字节码文件.pyc后缀,可以跨平台用

>>> from py_compile import compile

>>>compile(“hello.py”)


>>> x = 1 type可以看到x的类型

>>> print id(x)

159662256

>>> print x

1

>>> print type(x)

<type 'int'>


>>> from math import sqrt

>>> for i in range(99, 82, -1):

... res = sqrt(i)

... if res == int(res):

... print res

... break

... else:

... print "has not!"

...

has not!





>>> def func(*x):

print x


>>> a = (1, 2, 3)

>>> func(a)

((1, 2, 3),)

>>> func(1,2,3,4)

(1, 2, 3, 4)

>>> def func(a, b, c)

SyntaxError: invalid syntax

>>> def func(a, b, c):

print a, b, c


>>> func(a)

Traceback (most recent call last):

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

func(a)

TypeError: func() takes exactly 3 arguments (1 given)

>>> func(*a)

1 2 3


>>> class TestIterator: 超级注意,迭代器的实现

value = 0

def next(self):

self.value += 1

if self.value > 10 : raise StopIteration

return self.value

def __iter__(self):

return self

>>> ti = TestIterator()

>>> list(ti)

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

>>>


>>> class Fibs:

def __init__(self):

self.a = 0

self.b = 1

def next(self):

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

return self.a

def __iter__(self):

return self

>>> fibs = Fibs()

>>> for f in fibs:

if f > 1000:

print f

break

1597


class A:
    def __init__(self):
        print("Enter A")
        print("Leave A")

class B(A):
    def __init__(self):
        print("Enter B")
        A.__init__(self)
        print("Leave B")

class C(A):
    def __init__(self):
        print("Enter C")
        A.__init__(self)
        print("Leave C")

class D(A):
    def __init__(self):
        print("Enter D")
        A.__init__(self)
        print("Leave D")

class E(B, C, D):
    def __init__(self):
        print("Enter E")
        B.__init__(self)
        C.__init__(self)
        D.__init__(self)
        print("Leave E")

E()


结果:

Enter E
Enter B
Enter A
Leave A
Leave B
Enter C
Enter A
Leave A
Leave C
Enter D
Enter A
Leave A
Leave D
Leave E


执行顺序很好理解,唯一需要注意的是公共父类A被执行了多次。

代码二:

class A:
    def __init__(self):
        print("Enter A")
        print("Leave A")

class B(A):
    def __init__(self):
        print("Enter B")
        super(B, self).__init__()
        print("Leave B")

class C(A):
    def __init__(self):
        print("Enter C")
        super(C, self).__init__()
        print("Leave C")

class D(A):
    def __init__(self):
        print("Enter D")
        super(D, self).__init__()
        print("Leave D")

class E(B, C, D):
    def __init__(self):
        print("Enter E")
        super(E, self).__init__()
        print("Leave E")

E()


结果:

Enter E
Enter B
Enter C
Enter D
Enter A
Leave A
Leave D
Leave C
Leave B
Leave E


super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.__mro__)。




上面的语句比较特别,在forif中,如果一直都没有找到的话,只好就退出for了,此时还留有if后的else执行,这样刚好就会执行else,但是如果在forif中找到了,运行break,此时因为if过,所以else会跳过


列表推到式

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

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

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

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


python中有垃圾回收机制的,并且python也提供了del让用户自己删除


execevalexec不返回东西,eval返回东西,eval输入的是字符串来计算,而exec是执行python的语句)

>>> s = {} 最好运行在全局字典中

>>> exec 'x = 2' in s 不会影响局部的变量

>>> eval('x * x', s)

4



函数的定义,其中放在定义下一行的''字符串用于表示如果使用的说明,函数名.__doc__ 可以返回

>>> def square(x):

... 'put an x to result x*x'

... return x*x

...

>>> square.__doc__

'put an x to result x*x'


>>> help(square) help函数可以帮组我们看很多东西有关某个函数的


可以用变量来约定参数的值

>>> def hello_1(greening, name):

... print greening, name

...

>>> hello_1("world", "hello")

world hello

>>> hello_1(name = "world", greening = "hello")

hello world


>>> def hello_1(greening = "world", name = "hello"):

... print name,greening

...

>>> hello_1()

hello world

>>> hello_1("aa")

hello aa

>>> hello_1(name = "aa")

aa world


收集参数(分可否处理关键字,*不行,**行)

>>> def hello_1(*ele):

... print ele

...

>>> hello_1("a")

('a',)

>>> hello_1("a", "b")

('a', 'b')

>>> hello_1(("a","b"))

(('a', 'b'),)

>>> def hello_1(**ele):

... print ele

...

>>> hello_1("a")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: hello_1() takes exactly 0 arguments (1 given)

>>> hello_1(a="a")

{'a': 'a'}

>>> hello_1(a="a", b="b")

{'a': 'a', 'b': 'b'}


>>> def hello_1(greeting, name): 反转的释放参数

... print greeting,name

...

>>> ele = ("hello", "world")

>>> hello_1(*ele)

hello world




½ 得到 0

1.0/2得到0.5

½.得到0.5

2**3得到8

-2**3得到-8

-2**3得到8


>>>10000000000000000000000000000000000000000 python长度没有限制

10000000000000000000000000000000000000000L


>>>x = input(“input num:”)

input num: 42

x: 42

>>>print x

42


>>> x = pow(2,3)

>>> print x

8


>>> abs(-10)

10

>>> round(1.0/2) 是四舍五入到整数

1.0


>>> from math import floor 小于浮点数的最大整数

>>> floor(2.1/2)

1.0

>>> int(floor(2.1/2)) int()是将其转换成整数

1


>>> import math 注意与前面的 from math import floor比较

>>> math.ceil(2.1/2) 大于浮点树的最大整数

2.0


>>> import math

>>> math.sqrt(1.0)

1.0

>>> math.sqrt(-1.0)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: math domain error

>>> import cmath

>>> cmath.sqrt(-1.0)

1j j表示虚数


>>> (1 + 3j) * (1 - 3j)

(10+0j)

>>> (1 + 3j) * (1 - 2j)

(7+1j)


>>>foo = math.sqrt 名字可以赋值

>>>foo(9)

3


>>> "hello"

'hello'

>>> "let's go"

"let's go"

>>> '"hello", world'

'"hello", world'

>>> 'let's go'

File "<stdin>", line 1

'let's go'

^

SyntaxError: invalid syntax

>>> 'let\'s go' \表示转意

"let's go"


>>> "let's go" 'Hello world' 可以链接的

"let's goHello world"


>>> "let's go" + 'Hello world'

"let's goHello world"


>>> print repr("hello world") //总而言之str,repr,``都会把值转为字符串

'hello world'

>>> print repr(1000L)

1000L

>>> print repr(1000)

1000

>>> print str("hello world")

hello world

>>> print str(1000L)

1000


>>> input("put name:") input输入的是数值,除非加“”或‘’表明字符串

put name:ghost raw_input输入的就是字符串

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "<string>", line 1, in <module>

NameError: name 'ghost' is not defined

>>> input("put name:")

put name:"ghost"

'ghost'

>>> input("put num:")

put num:3

3

>>> raw_input("put name:")

put name:ghost

'ghost'

>>> raw_input("put num:")

put num:3

'3'

>>> """sjidfo'sdfsdf \ 长字符串可用“”“开始和结尾,\可以分行写

... "hello",world \

... let's go"""

'sjidfo\'sdfsdf "hello",world let\'s go'


>>> print r"let\'s go" 在字符串前加r可不用转意内部

let\'s go

>>> print "let\'s go"

let's go

>>> print r'let\'s go'

let\'s go


>>> print u'let\'s go' 转换成unicode的编码

let's go



列表

>>> a = ['abc', 42] 列表内的元素可以不同类型,列表可以一个一个添加元素

>>> b = ['efg', '4'] 没有限制,就像c++vector等容器,

>>> c = [a, b]

>>> print a

['abc', 42]

>>> print b

['efg', '4']

>>> print c

[['abc', 42], ['efg', '4']]


>>> name = "ghost" 字符串也是一个序列,-1可以倒过来未最后一个(很特别)

>>> name[0]

'g'

>>> name[-1]

't'

>>> name[-2]

's'


>>> name = "ghost" 分片,区间为[x,y)

>>> name[0: 2]

'gh'

>>> name[0:-1]

'ghos'


>>> name[-3:-1] 要获取最后3个字符串,于是最后一个不写用[-3:]

'os'

>>> name[-3:0]

''

>>> name[-3:]

'ost'

>>> name[:]

'ghost'


>>> name[0:4:2] 分片可以跳转的,还可以逆跳转

'go'

>>> name[0:4:1]

'ghos'

>>> name[4:0:-1]

'tsoh'


>>> a = [1, '2'] 列表是可以组合的

>>> b = [1, 2]

>>> print a + b

[1, '2', 1, 2]


>>> 'python' * 5 序列可以做乘法运算

'pythonpythonpythonpythonpython'

>>> [42]*5

[42, 42, 42, 42, 42]


>>> len('python') 计算序列长度len()

6

>>> len([1,2,3])

3

>>> len((1,2,3))

3


>>> name = "ghost" 判断时候存在于序列中

>>> "os" in name

True

>>> name = [1, 2, 3]

>>> 1 in name

True


>>> min(4,2,3,9) 可以获取序列中的最大最小值

2

>>> max(4,2,3,9)

9

>>> name = "ghost"

>>> min(name)

'g'

>>> max(name)

't'

>>> a = [4,2,3,9]

>>> min(a)

2

>>> max(a)

9


>>> name = "ghost" 字符串变成列表用list()

>>> list(name)

['g', 'h', 'o', 's', 't']


>>> name = ["ghost", "sb", "python"] 删除列表中的元素del

>>> del name[1]

>>> print name

['ghost', 'python']

>>> name = ["ghost", "sb", "python"]

>>> del name[1:]

>>> name

['ghost']


>>> name = ["ghost", "sb", "python"] 元素插入列表

>>> name[1:1] = ["g", "gg"]

>>> name

['ghost', 'g', 'gg', 'sb', 'python']

>>> name[1:3] = [] 列表元素删除第二种方法

>>> name

['ghost', 'sb', 'python']



列表中的方法


>>> lst = [1,2,3] 尾部添加 append

>>> lst.append(3)

>>> lst

[1, 2, 3, 3]


>>> x = [[1,2],1,1,[1,[1,2]]] 元素计算个数 count

>>> x.count(1)

2


>>> a = [1,2,3] 尾部添加一个列表 extend

>>> b = [4,5,6]

>>> a.extend(b)

>>> a

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


>>> a = [1,2,3] 查找第一个符合元素的位置index,没则报错

>>> a.index(2)

1

>>> a.index(4)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: 4 is not in list


>>> x = [1,2,3] 插入 insert,超出范围放最后

>>> x.insert(2,"g")

>>> x.insert(6,"s")

>>> x

[1, 2, 'g', 3, 's']



>>> x = [1,2,3] 弹出pop(),LIFO,pop方法还可以带参数

>>> x.pop() 位置错了会报错

3

>>> x

[1, 2]

>>> x.pop(0)

1

>>> x

[2]

>>> x.pop(6)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: pop index out of range


>>> x = [1,2,3] 移除某一元素,位置错了会报错remove()

>>> x.remove(1)

>>> x.remove(5)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: list.remove(x): x not in list


>>> x = [1,2,3] 反向存储reverse() 是直接改变列表不返回

>>> x.reverse() y = x.reverse()是错误的,y还是空

>>> x >>> y = list(reversed(x))

[3, 2, 1] >>> y

[3, 2, 1] 这样可用


>>> x = [3, 2, 1] 排序sort(),排序页有reverse的问题,就是

>>> x.sort() 不返回任何值

>>> x

[1, 2, 3]

>>> x = ["gg", "gh", "ga", "gz", "a", "asdf"] len是长度函数,可以自己定义

>>> x.sort(key=len)

>>> x

['a', 'gg', 'gh', 'ga', 'gz', 'asdf']

>>> x = ["gg", "gh", "ga", "gz", "a", "asdf"] com为自己定义的函数

>>> x.sort(com)

>>> x = ["gg", "gh", "ga", "gz", "a", "asdf"] True可改为False,表示时候反向

>>> x.sort(reverse=True)

>>> x

['gz', 'gh', 'gg', 'ga', 'asdf', 'a']


>>> x = [3, 2, 1] 超级注意:区分有没有副本

>>> y = x[:] 其实列表的变量就是相当于指针

>>> x.sort()

>>> x

[1, 2, 3]

>>> y

[3, 2, 1]

>>> x = [3, 2, 1]

>>> y = x

>>> x.sort()

>>> x

[1, 2, 3]

>>> y

[1, 2, 3]

>>> x = 3 变量与上面的指针对比变量

>>> y = x

>>> y

3

>>> x = 4

>>> y

3


元组(不可变)


列表是可变的(但是元组是固定的)


>>> (1) 小心一个值的元组

1

>>> (1,)

(1,)

>>> 1,

(1,)

>>> (1, 2)

(1, 2)


>>> 3 * (42 + 2)

132

>>> 3 * (42 + 2,)

(44, 44, 44)


>>> tuple([1,2,3]) 转换成元组tuple(),就向list()转成列表

(1, 2, 3

>>> tuple("name")

('n', 'a', 'm', 'e')


>>> x = 1, 2, 3

>>> x[1]

2

>>> x[0:2]

(1, 2)


一般来说基本上能用列表就用列表,不用元组,但是必要情况下也是要元组的,例如

1)元组可以在映射(和集合的成员)中当作键使用—而别表则不行

2)元组作为很多内建函数和方法的返回值存在,也就是说你必须对元组进行处理。只要不尝试修改元组,那么,“处理”元组在绝大多数情况下就是把他们当作列表处理操作,除一些元组没有的方法如(index,count


>>> name = ('g', 'h', 'o', 's', 't') 元组不能被修改的

>>> name

('g', 'h', 'o', 's', 't')

>>> name[1,3] = "ab"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment




字符串


>>> name = "ghost" 字符串是不能被修改的

>>> name[1:3]

'ho'

>>> name[1:3] = "ab"

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: 'str' object does not support item assignment


>>> format = "hello, %s" %表示格式化输出

>>> name = "ghost"

>>> print format % "ghost"

hello, ghost

>>> name = "ghost",

>>> print format % name

hello, ghost

>>> name

('ghost',)

>>> format = "you have input num: %f"

>>> from math import pi

>>> print format % pi

you have input num: 3.141593

>>> format = "you have input num: %.2f"

>>> print format % pi

you have input num: 3.14


>>> from math import pi 转换类型

>>> '%10f' % pi

' 3.141593'

>>> '%10.2f' % pi

' 3.14'

>>> '%.5s' % "Guido van Rossum"

'Guido'

>>> '%.*s' % (4, "Guido van Rossum")

'Guid'

>>> '%010.2f' % pi

'0000003.14'

>>> '%-10.2f' % pi

'3.14 '

>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10) 前加空格,有助于区分正负

10

-10

>>> print ('%+d' % 10) + '\n' + ('%+d' % -10)

+10

-10


>>> str = "ghost ni hao a , wo bu hao" string的方法find()

>>> str.find(ni)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'ni' is not defined

>>> str.find("ni")

6

>>> str.find("n")

6

>>> str.find("asdf")

-1

>>> str.find("ni", 10, 23) find()方法提供起点和终点

-1

>>> str.find("ni", 10)

-1

>>> str.find("ni", 4)

6

>>> str.find("ni", 4, 5)

-1


>>> dir = ("", "usr", "local", "ghost") 字符串的join方法,插入

>>> "/".join(dir)

'/usr/local/ghost'

>>> "~/".join(dir)

'~/usr~/local~/ghost'


>>> dir = ("", "usr", "local", "ghost") 字符串的split方法,分割

>>> myDir = "/".join(dir)

>>> myDir.split("/")

['', 'usr', 'local', 'ghost']


>>> name = "Ghost" 字符串lower方法,还有uppertitle等一堆

>>> name.lower()

'ghost'


>>> name = "this is my home" 替换replace方法

>>> name.replace("is", "eez")

'theez eez my home'


>>> name = " this is my home " 去左右空格strip方法,还有lstrip,rstrip

>>> name.strip()

'this is my home'


>>> from string import maketrans maketrans甚至可以处理其他lower无法

>>> table = maketrans('cs', 'kz') 改变的东西,作用比较打

>>> name = "this is my car"

>>> name.translate(table)

'thiz iz my kar'




字典


>>> name = [[1, "ghost"], [2, "jiaozi"]] 字典中的映射方法dict,就像列表的list

>>> a = dict(name) 元组中的tuple,还有字符串中的str

>>> a

{1: 'ghost', 2: 'jiaozi'}

>>> name = [(1, "ghost"), (2, "jiaozi")]

>>> a = dict(name)

>>> a

{1: 'ghost', 2: 'jiaozi'}

>>> a = dict(name1 = "ghost", name2 = "jiaozi")

>>> a

{'name2': 'jiaozi', 'name1': 'ghost'}


很多函数类似于列表的如:len等,


>>> name = {}

>>> name[42] = "ghost"

>>> name[42]

'ghost'


>>> phonebook = \ 字典的格式化字符串

... {'Beth': '9120', 'Alice': '2341'}

>>> phonebook

{'Beth': '9120', 'Alice': '2341'}

>>> "Beth's phone number is %(Beth)s" % phonebook

"Beth's phone number is 9120"


>>> name 字典清除方法clear

{1: 'ghost', 2: 'jiaozi'}

>>> name.clear()

>>> name

{}

>>> x = {} 超级注意,其实就是指针问题,x = {}

>>> y = x 实就是讲另外一个新的指针赋予x,所以这

>>> x[1] = "ghost" 就是clear的作用所在

>>> y

{1: 'ghost'}

>>> x = {}

>>> y

{1: 'ghost'}

>>> x = {}

>>> y = x

>>> x[1] = "ghost"

>>> y

{1: 'ghost'}

>>> x.clear()

>>> y

{}


>>> name = {} 与列表,元组,字符串不同,不能[:],只能用copy方法

>>> name[1] = "ghost"

>>> name[2] = "xiaolin"

>>> name

{1: 'ghost', 2: 'xiaolin'}

>>> name[:]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type

>>> name.copy() 这里的copy方法是浅copy,如果有嵌套另外已成字典,

{1: 'ghost', 2: 'xiaolin'} 列表等的话,嵌套的其实就是copy指针,可以用引入深

copy,如,from copy import deepcopy,但是这是

一个方法而已,如n = deepcopy(name)


>>> {}.fromkeys(("n1", "n2")) 建立键方法fromkeys

{'n1': None, 'n2': None}

>>> {}.fromkeys(["n1", "n2"])

{'n1': None, 'n2': None}

>>> {}.fromkeys(["n1", "n2"], "ggg")

{'n1': 'ggg', 'n2': 'ggg'}


>>> name = {} 以键获取值方法,get,越界不会报错

>>> name[1] = "ghost"

>>> name[2] = "jiaozi"

>>> name[3]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 3

>>> name[2]

'jiaozi'

>>> name.get(2)

'jiaozi'

>>> name.get(3)

>>> name.get(3, "N/A") 注意

'N/A'


>>> name = ["ghost", "xiaolin"] 超级注意,列表中如果也直接用index方法会

>>> "ghost" in name 报错,所以先用in来判断时候存在最好

True

>>> name.index("g")

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: 'g' is not in list



>>> name.has_key(3) 可以用has_key方法来检查是否有该键

False



>>> name items返回列表的形式,里面用元组装键值对

{1: 'ghost', 2: 'jiaozi'} iteritemsitems相似,但是返回的是迭代

>>> name.items() iteritemsitems更加高效

[(1, 'ghost'), (2, 'jiaozi')] keys方法返回的是键的列表

>>> it = name.iteritems() iterkeys方法式键的里表迭代器

>>> it 还有values,itervalues

<dictionary-itemiterator object at 0xb76b2a04>

>>> list(it)

[(1, 'ghost'), (2, 'jiaozi')]


>>> n pop方法要指定那个键,popitem则不用,

{1: 'ghost', 2: 'jiaozi'} popitem因此用于一个一个删除好。

>>> n.pop(1)

'ghost'

>>> n.popitem()

(2, 'jiaozi')


>>> name 更新字典中的东西

{1: 'ghost', 2: 'jiaozi'}

>>> n = {1: "xx"}

>>> name.update(n)

>>> name

{1: 'xx', 2: 'jiaozi'}

>>> n = {3: "as"}

>>> name.update(n)

>>> name

{1: 'xx', 2: 'jiaozi', 3: 'as'}




if,循环语句


>>> name1 = "ghost"

>>> name2 = "jiaozi"

>>> print name1,name2

ghost jiaozi


>>> import math as func

>>> func.sqrt(9)

3.0

>>> from math import sqrt as func

>>> func(9)

3.0


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

>>> x

1

>>> y

2

>>> z

3

>>> x, y = y, x 注意,直接转换都可以

>>> print x, y, z

2 1 3


>>> n = [1, 2]

>>> x, y = n

>>> print x,y

1 2

>>> n = (1, 2)

>>> x, y = n

>>> print x,y

1 2


下面的值在作为布尔表达式的时候,会被解析器看作假(false:

False None 0 “” () [] {}



>>> name = "my name is ghost"

>>> name.endswith("host")

True

>>> if name.endswith("ghost"):

... print "hello, ghost"

...

hello, ghost


if … : 判断语句的句型

elif … :

else:


>>> x = y = [1,2,3]

>>> z = [1,2,3,]

>>> z

[1, 2, 3]

>>> x is y

True

>>> x is z

False

>>> x == y

True

>>> x == z

True

>>> x = 1

>>> x = y = 1

>>> z = 1

>>> x is y

True

>>> x is z

True


a if b else c

如果b真则返回a,否则返回c


>>> x = 10 断言,assert

>>> assert 0 < x <10

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AssertionError

>>> x = 9

>>> assert 0 < x <10




while语句


>>> name = ""

>>> while not name:

... name = raw_input("input your name:")

...

input your name:ghost

>>> name

'ghost'


for语句

>>> num = [1,2,3,4,5,6]

>>> for i in num:

... print i

...

1

2

3

4

5

6

>>> num = (1,2,3,4,5,6)

>>> for i in num:

... print i

...

1

2

3

4

5

6


>>> for i in range(0, 4): 可以用一个range来制造一个列表

... print i

...

0

1

2

3


>>> range(4)

[0, 1, 2, 3]


>>> name = ["ghost", "xiaolin"] 压缩两个列表的函数zip

>>> age = ["21", "20"]

>>> zip(name, age)

[('ghost', '21'), ('xiaolin', '20')]

>>> age = ("21", "20")

>>> name = ("ghost", "xiaolin")

>>> zip(name,age)

[('ghost', '21'), ('xiaolin', '20')]


>>> zip(range(5), xrange(100000000)) 绝对要用xrange,不然卡死

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

>>> zip(range(5), range(100000000))

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

>>>


>>> name enumerate可以用于for,方便

['ghost', 'xiaolin']

>>> list(enumerate(name))

[(0, 'ghost'), (1, 'xiaolin')]


>>> sorted(name) sorted函数是有返回的与sort方法不一样(直接改)

['ghost', 'xiaolin'] reversed函数是有返回的(迭代)reverse方法不一样(直接改)

>>> n = "xiaolin"

>>> sorted(n)

['a', 'i', 'i', 'l', 'n', 'o', 'x']

>>> reversed(n)

<reversed object at 0xb7822b2c>

>>> list(reversed(n))

['n', 'i', 'l', 'o', 'a', 'i', 'x']


>>> range(10, 0)

[]

>>> range(10, 0, -1)

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

>>> range(0, 10, 2)

[0, 2, 4, 6, 8]


>>> if 1 && 2: 与用and, 或用or, 非用not

File "<stdin>", line 1

if 1 && 2:

^

SyntaxError: invalid syntax

>>> if 1 and 2:

... print 2

...

2




抽象


>>> x = 1 判断是可以调用的函数么

>>> callable(x)

False

>>> import math

>>> callable(sqrt)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'sqrt' is not defined

>>> callable(math.sqrt)

True


>>> x = 1 其实赋值语句就是不可见的字典,vars函数是内建的,可以返回字典

>>> s = vars()

>>> s['x']

1


>>> x = 1 需要告知为全局变量,不然就重新创一个局部x

>>> def changeX():

global x

x += 1

>>> changeX()

>>> x

2


>>> from random import choice 随便抽取一个choice函数

>>> x = choice(['hello, world', ["ghost", "jiaozi"]])

>>> x

['ghost', 'jiaozi']


>>> class A: 超级注意,属性或方法名前用__可以表示如c++private

__a = 1 但不是绝对访问不到,用对象._类名__变量名 就可以访问了

def getA(self):

return self.__a


>>> a = A()

>>> a.getA()

1

>>> a._A__a

1



>>>class A:                                mem相当于c++类中的static,__mem1才是私有成员
	mem  = 0		         但是如果实例化一个对象a后,改变a.mem,不会影响到A.mem
	__mem1 = 1                       

>>>issubclass(Derived, Base)             issubclass可以查看Derived时候是Base的子类
True

>>>Derived.__bases__                     __bases__ 特性可以直接查看基类们

>>>d = Derived()                         isinstance可以查看是否为某个类的实例对象
>>>isinstance(d, Derived)
True
>>>isinstance(d,Base)
True


>>>d.__class__                           __class__ 特性可以查看是哪个类的对象

>>>class MulDerived(Base1, Base2):       多继承的定义,要注意,如果Base1Base2中有方法名                  一样,那么只存在Base1的方法

>>>hasattr(d, 'talk')                    d的对象中,如果有talk函数,则返回True,如果没就返回False    
True 
>>>callable(getattr(tc, 'talk', None))   检查d中的对象的函数talk是否可以调用(3.0中已经用hasattr代替了)

>>>d.__dict__                            __dict__ 特性可以查看对象内所有存储的值

>>>raise Exception                         自己控制抛出异常
>>>raise Execption("hyperdrive overload")

>>>import exceptions                     exceptions模块中有很多异常类,dir()函数可以看到包含的类
>>>dir(exceptions)   




class MuffledCalculator: 对于想再抛出接受到的异常,可以直接只用raise

muffled = False

def calc(self, expr):

try:

return eval(expr)

except ZeroDivisionError:

if self.muffled:

print "Division by zero"

else:

raise


>>> try: 可以设置多个execpt

x = input("input an interage")

x/y

except ZeroDivisionError:

print "error div a zero"

except TypeError:

print "input an error type"


>>> try: 可以一个块多个异常

x = input("input an interage")

x/y

except (ZeroDivisionError, TypeError, NameError):

print "error"



>>> try: 捕捉错误对象

x = input("input an interage")

x/y

except (ZeroDivisionError, TypeError, NameError), e:

print e


input an interagea

name 'a' is not defined


>>> try: 直接只用except什么都可以获取到

x = input("input an interage")

x/y

except (ZeroDivisionError, TypeError), e:

print e

except:

print "wrong"



try: try/except/else语句中,else只有在没有错时执行

x = input("input an interage")

y = input("input an interage")

x/y

except (ZeroDivisionError, TypeError), e:

print e

except:

print "wrong"

else:

print "ok"



特殊方法


__init__ 相当于c++的构造函数

__del__ 相当与c++的析构函数

父类名.__init__(self,可以有参数) 在子类的构造函数中调用父类的构造函数的方法(旧的用法)

super(当前类名, self).__init__(可以有参数) 在子类的构造函数中调用父类的构造函数的方法(新)

__getitem__(self, key) 获取指定的key键下表的值 如x = s[2]

__setitem__(self, key, value) 设置指定的key键下表的值 如s[2] = x

__delitem__ (self, key) 删除指定的key下的元素 如del s[2]

property(fget, fset, fdel, doc) 设置成函数像变量一样运用

可以单独只用一个,如size = property(fset = setSize) 后面有例子

__setattr__(self, name, value) 用于 对象名.变量名(name)= 值(value

__getattr__(self, name, value) 用于 对象名.变量名(name) 当对象没有此变量名时才被调用


__str__(self) 用于 print 对象名 或者 str(对象名)

__mro__ 使用的,用于查看继承的东西(distinctdict继承了dict

>>> distinctdict.mro()

[<class '__main__.distinctdict'>, <type 'dict'>, <type 'object'>]


迭代器规则在python3.0中有一些变化。在新的规则中,迭代起对象应该实现__next__方法,而不是next(),二新的内建函数next可以用于访问这个方法。换句话说,next(it)等同于3.0之前的it.next()

__iter__(self)

__new__(cls) 可以用来判断时候新建了该类,继承的时候

>>> class B: 其他方法都可以用super调用父的方法

def __init__(self, num):

self.num = num

def setNum(self, num, num2):

self.num = num

self.num2 = num2


>>> class D(B):

def __init__(self, num):

super(D, self).__init__(num)

def setNum(self, num):

self.num2 = num


>>> class Rectangle:

def __init__(self):

self.width = 0

self.height = 0

def setSize(self, size):

self.width, self.height = size

def getSize(self):

return self.width, self.height

size = property(getSize, setSize)

>>> r = Rectangle()

>>> r.width = 10

>>> r.height = 5

>>> r.size

(10, 5)

>>> r.size = 150, 100

>>> r.width

150


>>> class Rectangle:

def __init__(self):

self.width = 0

self.height = 0

def setSize(self, size):

self.width, self.height = size

def getSize(self):

return self.width, self.height

size = property(fset = setSize)


>>> r = Rectangle()

>>> r.width = 10

>>> r.height = 5

>>> r.size

Traceback (most recent call last):

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

r.size

AttributeError: unreadable attribute

>>> r.size = 150,100

>>> r.width

150







静态方法与类成员方法


>>> class B:

@staticmethod

def b():

print "b"

@classmethod

def c(cls):

print "c", cls

def d(self):

print "d", self


>>> B.b()

b

>>> B.c()

c <class '__main__.B'>

>>> B.d()

Traceback (most recent call last):

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

B.d()

TypeError: unbound method d() must be called with B instance as first argument (got nothing instead)

>>> b = B()

>>> b.b()

b

>>> b.c()

c <class '__main__.B'>

>>> b.d()

d <__main__.B object at 0x8ac5acc>



  class Book(object): __setattr__, __getattr__, __str__魔法

  def __setattr__(self, name, value):

  if name == 'value':

  object.__setattr__(self, name, value - 100)

  else:

  object.__setattr__(self, name, value)

  def __getattr__(self, name):

  try:

  return object.__getattribute__(name)

  except:

  return name + ' is not found!'

  def __str__(self):

  return self.name + ' cost : ' + str(self.value)

  c = Book()

  c.name = 'Python'

  c.value = 100

  print c.name

  print c.value

  print c

  print c.Type

  上面的例子中,在赋值书的value属性时,偷偷的将value减去了100,呵。输出结果:

  Python

  0

  Python cost : 0

  Type is not found!



>>> class TestIterator: 超级注意,迭代器的实现

value = 0

def next(self):

self.value += 1

if self.value > 10 : raise StopIteration

return self.value

def __iter__(self):

return self

>>> ti = TestIterator()

>>> list(ti)

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

>>>


>>> class Fibs:

def __init__(self):

self.a = 0

self.b = 1

def next(self):

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

return self.a

def __iter__(self):

return self

>>> fibs = Fibs()

>>> for f in fibs:

if f > 1000:

print f

break

1597







生成器




任何包含yield语句的函数成为生成器。每次产生一个值(使用yield语句),函数就会被冻结:即函数停在那点等待被激活。函数被激活后就从停止的那点开始执行。在我认为,__iter__是用于类的迭代器,那么yield就是应用于函数的迭代器


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

>>> def flatten(nested):

for sublist in nested:

for element in sublist:

yield element

>>> for num in flatten(nested):

print num

1

2

3

4

5



__all__ = [“Error”, “copy”, “deepcopy”]

这个__all__特性用于from copy import * 星号表示导入__all__中的所有东西

如果没有设定__all__,用import * 语句默认将会输出模块中所有不以下划线开头的全局变量



import fileinput 模块是用于读取文件的 P196





集合(set

集合是可变的,因此不能做键值,另外其元素也只能是不可变的


>>> set([1,2,3,4,5]) 集合可以由序列(或者其他可以迭代的对象)构建的

set([1, 2, 3, 4, 5])

>>> set((1,2,3,4,1,2))

set([1, 2, 3, 4])

>>> set("ghostsdjfioagahoi")

set(['a', 'd', 'g', 'f', 'i', 'h', 'j', 'o', 's', 't'])


>>> a = set()

>>> b = set()

>>> a.add(b)

Traceback (most recent call last):

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

a.add(b)

TypeError: unhashable type: 'set'



>>> a = set([1,2,3]) set中,某些函数可以用运算符代替

>>> b = set([2,3,4])

>>> c = a & b

>>> c.issubset(a)

True

>>> c <= a

True

>>> c.issuperset(a)

False

>>> c <= a

True

>>> a.intersection(b)

set([2, 3])

>>> a & b

set([2, 3])

>>> a.difference(b)

set([1])

>>> a - b

set([1])

>>> a.symmetric_difference(b)

set([1, 4])

>>> a ^ b

set([1, 4])

>>> a.copy() is a

False


堆(heap


python中并没有独立的堆类型--只有一个包含一些堆操作函数的模块,这个模块叫heapq(qqueue的缩写),包含6个函数


>>> import heapq

>>> x = range(10)

>>> x

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

>>> h = []

>>> for n in range(len(x)):

heapq.heappush (h, n)

>>> h

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


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

>>> heapq.heapify (h)

>>> h

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




双端队列(deque


双端队列可以由序列(或者其他可以迭代的对象)构建的


>>> from collections import deque

>>> q = deque(range(5))

>>> q.append(5)

>>> q.appendleft(6)

>>> q

deque([6, 0, 1, 2, 3, 4, 5])

>>> q.pop ()

5

>>> q.popleft ()

6

>>> q.rotate(3)

>>> q

deque([2, 3, 4, 0, 1])

>>> q.rotate(-1)

>>> q

deque([3, 4, 0, 1, 2])






shelve模块(简单键值文件存储)


需要小心注意的是用append方法添加的时候只是添加到副本上,所以如果要用它添加就在打开文件的时候用writeback参数设置为True,因为默认为False

>>> s = shelve.open("/home/ghost/shelve.txt")

>>> s

{}

>>> s['x'] = [1, 2, 3]

>>> s['x']

[1, 2, 3]

>>> s['x'] = [1, 2, 3, 4]

>>> s['x']

[1, 2, 3, 4]

>>> s['x'].append(4)

>>> s

{'x': [1, 2, 3, 4]}

>>> s['x']

[1, 2, 3, 4]

>>> s['x'].append(5)

>>> s

{'x': [1, 2, 3, 4]}

>>> s['x']

[1, 2, 3, 4]

>>> s.close()

>>> sh = shelve.open("/home/ghost/shelve.txt")

>>> sh['x']

[1, 2, 3, 4]

>>> s = shelve.open(filename = "/home/ghost/shelve.txt", writeback = True)

>>> s

{'x': [1, 2, 3, 4]}

>>> s['x'].append(5)

>>> s['x']

[1, 2, 3, 4, 5]



正则


匹配对象和组

'There (was a (wee)(cooper)) who (lived in Fyfe)'

0 There was a wee cooper who lieved in Fyfe

1 was a wee cooper

2 wee

3 cooper

4 lived in Fyfe


>>> import re 匹配对象和组

>>> m = re.match(r'www\.(.*)\..{3}', 'www.python.org')

>>> m.group(1)

'python'

>>> m.group(0)

'www.python.org'

>>> m.start(1)

4

>>> m.end(1)

10

>>> m.span(1)

(4, 10)


>>> emphasis_pattern = r'\*([^\*]+)\*'

>>> re.sub(emphasis_pattern, r'<em>\1<em>', 'hello, *world*')

'hello, <em>world<em>'






贪婪版本(用?实现非贪婪)

>>> emphasis_pattern = r'\*(.+)\*'

>>> re.sub(emphasis_pattern, r'<em>\1<em>', '*this* is *it*')

'<em>this* is *it<em>'

>>> emphasis_pattern = r'\*(.+?)\*'

>>> re.sub(emphasis_pattern, r'<em>\1<em>', '*this* is *it*')

'<em>this<em> is <em>it<em>'



open函数用来打开文件

open(name[, mode[, buffering]])

r’ 读模式

'w' 写模式

'a' 追加模式

'b' 二进制模式(可添加到其他模式中使用)

'+' /写模式(可添加到其他模式中使用)

open的第三个参数,可以控制文件的缓冲,0表示不用缓存。所有读写操作直接针对硬盘,如果式1或者TrueI/O就是有缓冲的,只有使用flush或者close的时候才会更新硬盘上的数据,大于1的数据表示缓冲区的字节大小,-1或者其他负数,表示默认缓冲区的大小


>>> f = open("/home/ghost/had.txt", "r")

>>> f.read(4)

'1 84'

>>> f.read() 会一直读到尾

'69308861804289383\n2 17146369151681692777\n3 4242383351957747793\n4 1649760492719885386\n5 1189641421596516649\n6 13504900271025202362\n7 1102520059783368690\n8 19675139262044897763\n9 15403834261365180540\n10 1303455736304089172\n11 52159536835005211\n12 1726956429294702567\n13 861021530336465782\n14 233665123278722862\n15 4687031352145174067\n16 18019798021101513929\n17 6357230581315634022\n18

>>> f.tell() tell方法返回当前位置

23880L

>>>for line in f.xreadlines(): readlines是迭代器


>>>sys.stdin.read() 从标准输入中读取



with open("/home/ghost/had.txt", "w") as f: with语句可以在执行语句后自动关闭文件










数据库

import MySQLdb    mysql数据库的链接

conn = MySQLdb.connect (host = "127.0.0.1", user = "root", passwd = "pass", db = "im")

cursor = conn.cursor ()

cursor.execute ("SELECT VERSION()")

row = cursor.fetchone ()  

print "server version:", row[0]

cursor.close ()  

conn.close ()  




socket套接字



>>>import urllib 可以获取网址的html文件

>>>web = urllib.urlopen("http://www.baidu.com")

>>>test = web.read()


返回文件到指定路径

>>> urllib.urlretrieve("http://www.baidu.com", "/home/ghost/gh.txt")


原文地址:https://www.cnblogs.com/ghost240/p/2526735.html