python参考手册--第1章python简介
1.if __name__ == \’__main__\’:
直接运行myModel.py时,当前模块的名字是main;import myModel然后运行的时候当前模块的名字是myModel。
2.eval: eval 函数的功能是将字符串生成语句并执行。
3.from module import class/func
module对应*.py文件,里面可以有class、func。class下还可以有func
4.利用set去重:links = [link for link in set(links)]
5.利用正则表达式匹配之后,根据组名取出值:
(?P<item_count>\d+)是一个分组,item_count是组名
ret = re.search(r\’count:\\'(?P<item_count>\d+)\\’\’, html)
item_count = 0 if not ret else int(ret.group(\’item_count\’))
6.python3,print作为函数使用:print(“hello”)
7.特殊变量_用于保存最后一次运算的结果
>>>600+100
700
>>>_+200
900
8.格式化输出:
print “%3d %0.2f” %(year,b)
print (format(year,”%3d”),format(b,”%0.2f”))
print “{0:3d} {1:0.2f}”.format(year,b) #冒号前面的数字表示传递给format()方法的参数
9:python没有switch、case语句,使用多个if elif else 语句代替
10.for语句:for i in xrange(0,10)
11.按行读文件:
for line in open(“foo.txt”):
print line
print写文件:
f = open(“foo.txt”,w)
while year<=nmyears:
principal = principal * (1 + rate)
print >>f,”%3d %0.2f” % (year,principal)
year +=1
f.close()
python3中不能使用>>,用下面代替:
print (“%3d %0.2f” % (year,principal),file = f)
write写文件:
f.write(“%3d %0.2f\n” % (year,principal))
12.逻辑与、或、非:使用and、or、not
if a < 10 and a > :
print a
if b < 10 or b > 20:
print b
if not c
print c
13. utf8、gbk编码
>>> c=unicode(\’taobao_cocobella_35651013881_黑色\’,\’gbk\’).encode(\’utf8\’)
>>> c
\’taobao_cocobella_35651013881_\xe9\xbb\x91\xe8\x89\xb2\’
14.list、tuple、set、dict
list:可以增删,下标索引,连接。列表由于长度不固定,可增删,因此创建时会额外分配内存。
>>> a = [1,2,3,4,5]
>>> type(a)
<type \’list\’>
>>> a[2]
3
>>> len(a)
5
>>> b = []
>>> c = list()
>>> b.append(a)
>>> b
[[1, 2, 3, 4, 5]]
tuple:不能增删,可以下标检索,连接,可以解包成变量,sql查询返回的就是tuple。元组由于长度固定,因此创建时分配内存就是这么大,不会额外分配。
>>> a =1,2,3,4
>>> a
(1, 2, 3, 4)
>>> type(a)
<type \’tuple\’>
>>> b = (“hello”,)
>>> b
(\’hello\’,)
>>> b[0]
\’hello\’
>>> studentInfo = (\’Jack\’,24,\’China\’)
>>> name,age,country = studentInfo
>>> name
\’Jack\’
>>> age
24
>>> country
\’China\’
>>> d = b + studentInfo
>>> d
(\’hello\’, \’Jack\’, 24, \’China\’)
可以list与tuple合起来用:
>>>students = []
>>> students.append(studentInfo)
>>> Hanmeimei = (\’Hanmeimei\’,23,\’USA\’)
>>> students.append(Hanmeimei)
>>> students
[(\’Jack\’, 24, \’China\’), (\’Jack\’, 24, \’China\’), (\’Hanmeimei\’, 23, \’USA\’)]
set:集合是无序的,可以用于去重,但是不能进行下标索引。支持并集、交集、差集、对称差集等。用add增加一项,update增加多项
>>> a = set()
>>> b = set([1,2,3,4,5])
>>> type(b)
<type \’set\’>
>>> c = set([3,4,5,9,10,11])
>>> a = b | c
>>> d = b & c
>>> e = b – c
>>> f = b ^ c
>>> g = [a,d,e,f]
>>> g
[set([1, 2, 3, 4, 5, 9, 10, 11]), set([3, 4, 5]), set([1, 2]), set([1, 2, 9, 10, 11])]
>>> c.update([110,120,130])
>>> c
set([130, 3, 4, 5, 9, 10, 11, 110, 120])
>>> c.add(99)
>>> c
set([130, 3, 4, 5, 9, 10, 11, 110, 99, 120])
dict:字典,散列表。
>>> a = dict()
>>> b = {\’name\’:\’Jack\’,\’age\’:24,\’country\’:\’China\’}
>>> b
{\’country\’: \’China\’, \’age\’: 24, \’name\’: \’Jack\’}
>>> b[\’name\’]
\’Jack\’
15.range、xrange
python3中xrange完全替换了python2中的range,统一成了range
在python2中,range(1000) 会立刻填满数据0,1,2。。。999
而xrange(1000)不会立刻填满,根据需要填值,省内存些。
16.生成器
使用yield的函数都是生成器,使用func.next()生成结果序列
>>> def func(n):
print \’Count down func. n = %s\’ % n
while n > 0:
yield n
n -=1
>>> count = func(10)
>>> count.next()
Count down func. n = 10
10
>>> count.next()
9
>>> for i in func(10):
print i
Count down func. n = 10
10
9
8
7
6
5
4
3
2
1
17.协程
使用(yield)创建协程,将输入参数作为一组任务,从而能处理一切发送过来的输入:
>>> def print_matches(matchText):
print “looking for”,matchText
while True:
line = (yield)
if matchText in line:
print line
>>> matcher = print_matches(\’China\’)
>>> matcher.next()
looking for China
>>> matcher.send(\’fajsodfjaosidjfwodkfichafa asofjaofjwoijfoajsdf\’)
>>> matcher.send(\’I borned in China\’)
I borned in China
>>> matcher.close()
17.对象与类
dir()函数列出对象的所有可用方法,是交互试验的有用工具。
>>> dir(matcher)
[\’__class__\’, \’__delattr__\’, \’__doc__\’, \’__format__\’, \’__getattribute__\’, \’__hash__\’, \’__init__\’, \’__iter__\’, \’__name__\’, \’__new__\’, \’__reduce__\’, \’__reduce_ex__\’, \’__repr__\’, \’__setattr__\’, \’__sizeof__\’, \’__str__\’, \’__subclasshook__\’, \’close\’, \’gi_code\’, \’gi_frame\’, \’gi_running\’, \’next\’, \’send\’, \’throw\’]
>>> dir(dict())
[\’__class__\’, \’__cmp__\’, \’__contains__\’, \’__delattr__\’, \’__delitem__\’, \’__doc__\’, \’__eq__\’, \’__format__\’, \’__ge__\’, \’__getattribute__\’, \’__getitem__\’, \’__gt__\’, \’__hash__\’, \’__init__\’, \’__iter__\’, \’__le__\’, \’__len__\’, \’__lt__\’, \’__ne__\’, \’__new__\’, \’__reduce__\’, \’__reduce_ex__\’, \’__repr__\’, \’__setattr__\’, \’__setitem__\’, \’__sizeof__\’, \’__str__\’, \’__subclasshook__\’, \’clear\’, \’copy\’, \’fromkeys\’, \’get\’, \’has_key\’, \’items\’, \’iteritems\’, \’iterkeys\’, \’itervalues\’, \’keys\’, \’pop\’, \’popitem\’, \’setdefault\’, \’update\’, \’values\’, \’viewitems\’, \’viewkeys\’, \’viewvalues\’]
>>> dir(set())
[\’__and__\’, \’__class__\’, \’__cmp__\’, \’__contains__\’, \’__delattr__\’, \’__doc__\’, \’__eq__\’, \’__format__\’, \’__ge__\’, \’__getattribute__\’, \’__gt__\’, \’__hash__\’, \’__iand__\’, \’__init__\’, \’__ior__\’, \’__isub__\’, \’__iter__\’, \’__ixor__\’, \’__le__\’, \’__len__\’, \’__lt__\’, \’__ne__\’, \’__new__\’, \’__or__\’, \’__rand__\’, \’__reduce__\’, \’__reduce_ex__\’, \’__repr__\’, \’__ror__\’, \’__rsub__\’, \’__rxor__\’, \’__setattr__\’, \’__sizeof__\’, \’__str__\’, \’__sub__\’, \’__subclasshook__\’, \’__xor__\’, \’add\’, \’clear\’, \’copy\’, \’difference\’, \’difference_update\’, \’discard\’, \’intersection\’, \’intersection_update\’, \’isdisjoint\’, \’issubset\’, \’issuperset\’, \’pop\’, \’remove\’, \’symmetric_difference\’, \’symmetric_difference_update\’, \’union\’, \’update\’]
>>> dir(list())
[\’__add__\’, \’__class__\’, \’__contains__\’, \’__delattr__\’, \’__delitem__\’, \’__delslice__\’, \’__doc__\’, \’__eq__\’, \’__format__\’, \’__ge__\’, \’__getattribute__\’, \’__getitem__\’, \’__getslice__\’, \’__gt__\’, \’__hash__\’, \’__iadd__\’, \’__imul__\’, \’__init__\’, \’__iter__\’, \’__le__\’, \’__len__\’, \’__lt__\’, \’__mul__\’, \’__ne__\’, \’__new__\’, \’__reduce__\’, \’__reduce_ex__\’, \’__repr__\’, \’__reversed__\’, \’__rmul__\’, \’__setattr__\’, \’__setitem__\’, \’__setslice__\’, \’__sizeof__\’, \’__str__\’, \’__subclasshook__\’, \’append\’, \’count\’, \’extend\’, \’index\’, \’insert\’, \’pop\’, \’remove\’, \’reverse\’, \’sort\’]
>>> dir((1,2,3,4))
[\’__add__\’, \’__class__\’, \’__contains__\’, \’__delattr__\’, \’__doc__\’, \’__eq__\’, \’__format__\’, \’__ge__\’, \’__getattribute__\’, \’__getitem__\’, \’__getnewargs__\’, \’__getslice__\’, \’__gt__\’, \’__hash__\’, \’__init__\’, \’__iter__\’, \’__le__\’, \’__len__\’, \’__lt__\’, \’__mul__\’, \’__ne__\’, \’__new__\’, \’__reduce__\’, \’__reduce_ex__\’, \’__repr__\’, \’__rmul__\’, \’__setattr__\’, \’__sizeof__\’, \’__str__\’, \’__subclasshook__\’, \’count\’, \’index\’]
类的派生:
class Student(Person):
def __init__(self,sname):#构造函数
self.name = sname
def getName()
return self.name
@staticmethod
def studentNum()
pass
18.异常处理
(1)try except语句
try:
func()
excetp:
print “error!”
(2)raise手动抛异常
func(n):
if n < 0:
raise valueError(“n < 0”)
这样调用func的地方就可以通过try捕获异常
(3)with语句
import threading
message_lock = threading .Lock()
…
with message_lock:
message.add(newMessage)
with语句自动获取message_lock对象,当执行离开with代码块后(即message.add(newMessage)),后面的对象message_lock自动释放。无论with语句内部是否发生异常都将会释放该message_lock。有点类似于java中的finally语句。
19.模块
module.py文件作为一个模块,模块里面可以有class、普通方法(区别于类成员函数)
(1)import module #导入模块
(2)from module import funcOrClass #导入模块中的方法及类
(3)import module as otherModuleName #使用别名导入模块
20.帮助信息
(1)help
>>> help(set)
Help on class set in module __builtin__:
class set(object)
| set() -> new empty set object
| set(iterable) -> new set object
|
| Build an unordered collection of unique elements.
|
| Methods defined here:
|
| __and__(…)
| x.__and__(y) <==> x&y
|
| __cmp__(…)
| x.__cmp__(y) <==> cmp(x,y)
|
| __contains__(…)
| x.__contains__(y) <==> y in x.
|
| __eq__(…)
| x.__eq__(y) <==> x==y
。。。
(2)__doc__
>>> print list.__doc__
list() -> new empty list
list(iterable) -> new list initialized from iterable\’s items