python story

32
Python Story 陈陈陈 <[email protected]> twitter: @nnfish blog: http://chenxiaoyu.org

Upload: small-fish

Post on 19-May-2015

2.939 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Python story

Python Story

陈小玉 <[email protected]>twitter: @nnfishblog: http://chenxiaoyu.org

Page 2: Python story

历史由来阿姆斯特丹1989 年圣诞节期间Guido van Rossum 为了打发圣诞节的无趣决心开发一种新的解释性程序

不久之后,一个叫 Python 的语言就诞生了!

注: Guido 又称龟叔或者莽爹 :_)

Page 3: Python story

能做什么• 系统编程• GUI 应用• 网络应用• 数据库应用• WEB 应用• 快速开发模型• 游戏、人工智能、图像等• … more

Page 4: Python story

谁在用• Google• YouTube• Bittorrent• Facebook• Digg• Dropbox• Opera• Reddit• Sourceforge• 豆瓣• 搜狐邮箱• 金山• … more

Page 5: Python story

优势• 免费、开源• 跨平台• 简单易学• 快速开发• 类库丰富• 易扩展• 可嵌入性

Page 6: Python story

版本信息• 2.x

• 2.5.4 推荐!• 2.6.5 推荐!• 2.7 2.x 最后一个版本

• 3.x• 3.1 不推荐,可以尝鲜• 2to3

Help: 官网下载怎么打不开了? * 翻墙下载 * http://code.google.com/p/smallfish 下载

Page 7: Python story

目录结构Windows• DLLs• Doc Python 帮助, Pyer 必看!• include• Lib Python 自带库的源码目录

• site-packages 第三方库安装目录• libs• Scripts 第三方库一些批处理和可执行的工具• tcl• Tools• LICENSE.txt• NEWS.txt• python.exe• pythonw.exe• README.txt• …

Page 8: Python story

优秀项目• Mercurial ( HG ) 分布式版本控制系统• Twisted 网络编程框架• Trac 项目管理工具和 WIKI 系统• ReviewBoard 代码 review 工具• Sphinx 文档工具• SQLAlchemy ORM 框架• Django 、 Pylons WEB 开发框架• Stackless 山寨版 Python• Google App Engine 平台• Cython 扩展工具

Page 9: Python story

hello, world

Page 10: Python story

语法特点• 缩进(建议 4 空格) IndentationError

• 面向对象和面向过程• Pythonic 哲学,请参看: http://www.slideshare.net/nnfish/pythonic

Page 11: Python story

代码截图

Page 12: Python story

序列( 1 )• list

>>> a = [1, 2, 3]>>> print a[1, 2, 3]>>> print a[0]1>>> a[2] = 10>>> print a[1, 2, 10]

• tuple>>> b = (1, 2, 3)>>> print b, b[1](1, 2, 3) 2>>> b[1] = 20Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment

Page 13: Python story

序列( 2 )• str

>>> s = 'abcde'>>> print sabcde>>> print s[1]b>>> s[1] = 'd'Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment

Page 14: Python story

序列切片>>> a = 'abcd'>>> print a[1:3]bc>>> print a[1:]bcd>>> print a[:]abcd>>> print a[:3]abc>>> print a[:-1]abc>>> print a[-2]c

字符串反转>>> print a[::-1]dcba

a b c d

0 1 2 3

-4 -3 -2 -1

Page 15: Python story

字典( 1 )• dict

>>> c = {'name': 'smallfish', 'age': 20}>>> print c{'age': 20, 'name': 'smallfish'}>>> print c['name']smallfish>>> c['name'] = 'chenxiaoyu'>>> print c{'age': 20, 'name': 'chenxiaoyu'}>>> del c['age']>>> print c{'name': 'chenxiaoyu'}>>> c['address'] = 'China, Jiangsu'>>> print c{'name': 'chenxiaoyu', 'address': 'China, Jiangsu'}

Page 16: Python story

字典( 2 )• 格式化输出>>> c = {'name': 'smallfish', 'age': 20}>>> print "hello %s, your age is %d" % (c['name'], c['age'])hello smallfish, your age is 20

• 可以简单一点>>> print "hello %(name)s, your age is %(age)d" % chello smallfish, your age is 20

Page 17: Python story

集合• set

>>> a = set((1, 2, 3))>>> b = set((2, 4, 6))

>>> print aset([1, 2, 3])>>> print a, bset([1, 2, 3]) set([2, 4, 6])

>>> print a & bset([2])v

>>> print a | bset([1, 2, 3, 4, 6])

>>> print a ^ bset([1, 3, 4, 6])

去除某数组内重复数据a = ['aaa', 'bbb', 'ccc', 'aaa', 'ddd', 'aaa']>>> list(set(a)) ['aaa', 'bbb', 'ccc', 'ddd']

Page 18: Python story

流程控制if a == 1: print 'aaa'else: print 'bbb'

if b == 1: print '111'elif b == 2: print '222'else: print '000'

while a < 10: print a a += 1

for item in (1, 2, 3): print item

d = {'name': 'smallfish', 'age': 20}for k in d: print k, d[k]for k, v in d.items(): print k, v

输出age 20name smallfish

Page 19: Python story

函数( 1 )def hello(name): "hello function, name is param" print "hello", name

>>> print hello.__doc__hello function, name is param>>> hello('smallfish')hello smallfish

# 给函数参数加默认值def hello(name='smallfish'): # 同上代码

>>> hello()hello smallfish>>> hello('chenxiaoyu')hello chenxiaoyu

Page 20: Python story

函数( 2 )# 不定参数def hello(*args, **kwargs): print args print kwargs

>>> hello()(){}>>> hello(1, 2, 3)(1, 2, 3){}>>> hello(1, 2, 3, a='aa', b='bb')(1, 2, 3){'a': 'aa', 'b': 'bb'}>>>

Page 21: Python story

函数( 3 )lambda 函数

简单函数:def lowercase(x):

return x.lower()

其实可以这么写:lowercase = lambda x: x.lower()

Page 22: Python story

内置函数>>> help(re)Help on module re:NAME re - Support for regular expressions (RE).FILE d:\python27\lib\re.pyDESCRIPTION…>>> dir(re)['DEBUG', 'DOTALL', ..., 'sys', 'template']

>>> globals(){'a': 'abcd', '__builtins__': <module '__builtin__' (built-in)> … }

locals() vars() 输出基本同上

>>> type(re)<type 'module'>>>> type('aa')<type 'str'>

Page 23: Python story

Classclass User: def __init__(self, name): self.name = name def get_name(self): return self.name

>>> u = User('smallfish')>>> print u.get_name()smallfish

Page 24: Python story

模块# user.pydef hello(name): print 'hello', name

class User: def __init__(self, name): self.name = name def get_name(self): return self.name

>>> import user>>> dir(user)['User', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello']>>> user.hello('smallfish')hello smallfish>>> u = user.User('smallfish')>>> print u.get_name()smallfish

Page 25: Python story

列表推导List Comprehension (适用于 dict , tuple , str )

过滤数组中除以 2 等于 0 的元素:tmp = []items = [1, 2, 3, 4, 5]for i in items: if i % 2 == 0: tmp.append(i)

# 其实可以这么做:>>> [item for item in items if item % 2 == 0][2, 4]

# 每个元素都乘以 2>>> [item * 2 for item in items][2, 4, 6, 8, 10]

Page 26: Python story

修饰器( 1 )Decorator , Python2.4 之后新加特性!

问题:想记录每个函数执行多少时间?def hello(): start = time.time() … run code print time.time() – start

是不是太丑了点?用修饰器吧。

先写一个包装函数:

def time_wrapper(func): def _wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) print func.__name__, time.time() – start return _wrapper

Page 27: Python story

修饰器( 2 )测试函数:def hello(n): sum = 0 for i in range(n): sum += I return sum

我们可以这样调用:a = time_wrapper(hello)print a(100)

这个不稀奇,还可以这样写:@time_wrapperdef hello(n): … 同上

>>> hello(1000000)hello 0.265000104904

Page 28: Python story

示例代码( 1 )• 交换值1)tmp = aa = bb = tmp

2)a, b = b, a

• 判断 key 是否在 dict 中1)if d.has_key(key):

2)if key in d:

Page 29: Python story

示例代码( 2 )• 数组转字典name = ["smallfish", "user_a", "user_b"]city = ["hangzhou", "nanjing", "beijing"]print dict(zip(name, city)){'user_b': 'beijing', 'user_a': 'nanjing', 'smallfish': 'hangzhou'}

还需要两次 for循环么?

• 输出文件with open("d:/1.log") as fp: line = fp.readline() print line

Page 30: Python story

示例代码( 3 )• 数据库操作>>> import psycopg2>>> db = psycopg2.connect("host=localhost user=smallfish password=xx dbname=test")>>> cursor = db.cursor()>>> cursor.execute('select version()')>>> print cursor.fetchall()[('PostgreSQL 8.4.4 on i486-pc-linux-gnu, compiled by GCC gcc-4.4.real (Debian 4.4.4-7) 4.4.4, 32-bit',)]>>> cursor.close()>>> db.close()

Page 31: Python story

其他资源• 《 A Byte of Python》(中文名: Python 简明教程)• 《 Python Tutorial》( Python 官方手册,必读啊!)• 《 Python Style PEP-0008 》 http://www.python.org/dev/peps/pep-0008/

• 《 Pythonic》(更多有趣的写法) http://www.slideshare.net/nnfish/pythonic

Page 32: Python story

结束

print "Thanks!"

import sys

sys.exit(0)