Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Upcoming SlideShare
Saving Gaia with GeoDjango
Saving Gaia with GeoDjango
Loading in …3
×
1 of 32

Python story

11

Share

Download to read offline

Related Books

Free with a 30 day trial from Scribd

See all

Related Audiobooks

Free with a 30 day trial from Scribd

See all

Python story

  1. 1. Python Story 陈小玉 <smallfish.xy@gmail.com> twitter: @nnfish blog: http://chenxiaoyu.org
  2. 2. 历史由来 阿姆斯特丹 1989 年圣诞节期间 Guido van Rossum 为了打发圣诞节的无趣 决心开发一种新的解释性程序 … 不久之后,一个叫 Python 的语言就诞生了! 注: Guido 又称龟叔或者莽爹 :_)
  3. 3. 能做什么 <ul><li>系统编程 </li></ul><ul><li>GUI 应用 </li></ul><ul><li>网络应用 </li></ul><ul><li>数据库应用 </li></ul><ul><li>WEB 应用 </li></ul><ul><li>快速开发模型 </li></ul><ul><li>游戏、人工智能、图像等 </li></ul><ul><li>… more </li></ul>
  4. 4. 谁在用 <ul><li>Google </li></ul><ul><li>YouTube </li></ul><ul><li>Bittorrent </li></ul><ul><li>Facebook </li></ul><ul><li>Digg </li></ul><ul><li>Dropbox </li></ul><ul><li>Opera </li></ul><ul><li>Reddit </li></ul><ul><li>Sourceforge </li></ul><ul><li>豆瓣 </li></ul><ul><li>搜狐邮箱 </li></ul><ul><li>金山 </li></ul><ul><li>… more </li></ul>
  5. 5. 优势 <ul><li>免费、开源 </li></ul><ul><li>跨平台 </li></ul><ul><li>简单易学 </li></ul><ul><li>快速开发 </li></ul><ul><li>类库丰富 </li></ul><ul><li>易扩展 </li></ul><ul><li>可嵌入性 </li></ul>
  6. 6. 版本信息 <ul><li>2.x </li></ul><ul><ul><li>2.5.4 推荐! </li></ul></ul><ul><ul><li>2.6.5 推荐! </li></ul></ul><ul><ul><li>2.7 2.x 最后一个版本 </li></ul></ul><ul><li>3.x </li></ul><ul><ul><li>3.1 不推荐,可以尝鲜 </li></ul></ul><ul><ul><li>2to3 </li></ul></ul><ul><ul><li>Help: 官网下载怎么打不开了? </li></ul></ul><ul><ul><li>* 翻墙下载 </li></ul></ul><ul><ul><li>* http://code.google.com/p/smallfish 下载 </li></ul></ul>
  7. 7. 目录结构 <ul><li>Windows </li></ul><ul><li>DLLs </li></ul><ul><li>Doc Python 帮助, Pyer 必看! </li></ul><ul><li>include </li></ul><ul><li>Lib Python 自带库的源码目录 </li></ul><ul><ul><li>site-packages 第三方库安装目录 </li></ul></ul><ul><li>libs </li></ul><ul><li>Scripts 第三方库一些批处理和可执行的工具 </li></ul><ul><li>tcl </li></ul><ul><li>Tools </li></ul><ul><li>LICENSE.txt </li></ul><ul><li>NEWS.txt </li></ul><ul><li>python.exe </li></ul><ul><li>pythonw.exe </li></ul><ul><li>README.txt </li></ul><ul><li>… </li></ul>
  8. 8. 优秀项目 <ul><li>Mercurial ( HG ) 分布式版本控制系统 </li></ul><ul><li>Twisted 网络编程框架 </li></ul><ul><li>Trac 项目管理工具和 WIKI 系统 </li></ul><ul><li>ReviewBoard 代码 review 工具 </li></ul><ul><li>Sphinx 文档工具 </li></ul><ul><li>SQLAlchemy ORM 框架 </li></ul><ul><li>Django 、 Pylons WEB 开发框架 </li></ul><ul><li>Stackless 山寨版 Python </li></ul><ul><li>Google App Engine 平台 </li></ul><ul><li>Cython 扩展工具 </li></ul>
  9. 9. hello, world
  10. 10. 语法特点 <ul><li>缩进 (建议 4 空格) IndentationError </li></ul><ul><li>面向对象和面向过程 </li></ul><ul><li>Pythonic 哲学,请参看: http://www.slideshare.net/nnfish/pythonic </li></ul>
  11. 11. 代码截图
  12. 12. 序列( 1 ) <ul><li>list </li></ul><ul><ul><li>>>> a = [1, 2, 3] </li></ul></ul><ul><ul><li>>>> print a </li></ul></ul><ul><ul><li>[1, 2, 3] </li></ul></ul><ul><ul><li>>>> print a[0] </li></ul></ul><ul><ul><li>1 </li></ul></ul><ul><ul><li>>>> a[2] = 10 </li></ul></ul><ul><ul><li>>>> print a </li></ul></ul><ul><ul><li>[1, 2, 10] </li></ul></ul><ul><li>tuple </li></ul><ul><ul><li>>>> b = (1, 2, 3) </li></ul></ul><ul><ul><li>>>> print b, b[1] </li></ul></ul><ul><ul><li>(1, 2, 3) 2 </li></ul></ul><ul><ul><li>>>> b[1] = 20 </li></ul></ul><ul><ul><li>Traceback (most recent call last): </li></ul></ul><ul><ul><li>File &quot;<stdin>&quot;, line 1, in <module> </li></ul></ul><ul><ul><li>TypeError: 'tuple' object does not support item assignment </li></ul></ul>
  13. 13. 序列( 2 ) <ul><li>str </li></ul><ul><ul><li>>>> s = 'abcde' </li></ul></ul><ul><ul><li>>>> print s </li></ul></ul><ul><ul><li>abcde </li></ul></ul><ul><ul><li>>>> print s[1] </li></ul></ul><ul><ul><li>b </li></ul></ul><ul><ul><li>>>> s[1] = 'd' </li></ul></ul><ul><ul><li>Traceback (most recent call last): </li></ul></ul><ul><ul><li>File &quot;<stdin>&quot;, line 1, in <module> </li></ul></ul><ul><ul><li>TypeError: 'str' object does not support item assignment </li></ul></ul>
  14. 14. 序列切片 >>> 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
  15. 15. 字典( 1 ) <ul><li>dict </li></ul><ul><ul><li>>>> c = {'name': 'smallfish', 'age': 20} </li></ul></ul><ul><ul><li>>>> print c </li></ul></ul><ul><ul><li>{'age': 20, 'name': 'smallfish'} </li></ul></ul><ul><ul><li>>>> print c['name'] </li></ul></ul><ul><ul><li>smallfish </li></ul></ul><ul><ul><li>>>> c['name'] = 'chenxiaoyu' </li></ul></ul><ul><ul><li>>>> print c </li></ul></ul><ul><ul><li>{'age': 20, 'name': 'chenxiaoyu'} </li></ul></ul><ul><ul><li>>>> del c['age'] </li></ul></ul><ul><ul><li>>>> print c </li></ul></ul><ul><ul><li>{'name': 'chenxiaoyu'} </li></ul></ul><ul><ul><li>>>> c['address'] = 'China, Jiangsu' </li></ul></ul><ul><ul><li>>>> print c </li></ul></ul><ul><ul><li>{'name': 'chenxiaoyu', 'address': 'China, Jiangsu'} </li></ul></ul>
  16. 16. 字典( 2 ) <ul><li>格式化输出 </li></ul><ul><li>>>> c = {'name': 'smallfish', 'age': 20} </li></ul><ul><li>>>> print &quot;hello %s, your age is %d&quot; % (c['name'], c['age']) </li></ul><ul><li>hello smallfish, your age is 20 </li></ul><ul><li>可以简单一点 </li></ul><ul><li>>>> print &quot;hello %(name)s, your age is %(age)d&quot; % c </li></ul><ul><li>hello smallfish, your age is 20 </li></ul>
  17. 17. 集合 <ul><li>set </li></ul><ul><ul><li>>>> a = set((1, 2, 3)) </li></ul></ul><ul><ul><li>>>> b = set((2, 4, 6)) </li></ul></ul><ul><ul><li>>>> print a </li></ul></ul><ul><ul><li>set([1, 2, 3]) </li></ul></ul><ul><ul><li>>>> print a, b </li></ul></ul><ul><ul><li>set([1, 2, 3]) set([2, 4, 6]) </li></ul></ul><ul><ul><li>>>> print a & b </li></ul></ul><ul><ul><li>set([2])v </li></ul></ul><ul><ul><li>>>> print a | b </li></ul></ul><ul><ul><li>set([1, 2, 3, 4, 6]) </li></ul></ul><ul><ul><li>>>> print a ^ b </li></ul></ul><ul><ul><li>set([1, 3, 4, 6]) </li></ul></ul>去除某数组内重复数据 a = ['aaa', 'bbb', 'ccc', 'aaa', 'ddd', 'aaa'] >>> list(set(a)) ['aaa', 'bbb', 'ccc', 'ddd']
  18. 18. 流程控制 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 20 name smallfish
  19. 19. 函数( 1 ) def hello(name): &quot;hello function, name is param&quot; print &quot;hello&quot;, name >>> print hello.__doc__ hello function, name is param >>> hello('smallfish') hello smallfish # 给函数参数加默认值 def hello(name='smallfish'): # 同上代码 >>> hello() hello smallfish >>> hello('chenxiaoyu') hello chenxiaoyu
  20. 20. 函数( 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'} >>>
  21. 21. 函数( 3 ) lambda 函数 简单函数: def lowercase(x): return x.lower() 其实可以这么写: lowercase = lambda x: x.lower()
  22. 22. 内置函数 >>> help(re) Help on module re: NAME re - Support for regular expressions (RE). FILE d:ython27ibe.py DESCRIPTION … >>> dir(re) ['DEBUG', 'DOTALL', ..., 'sys', 'template'] >>> globals() {'a': 'abcd', '__builtins__': <module '__builtin__' (built-in)> … } locals() vars() 输出基本同上 >>> type(re) <type 'module'> >>> type('aa') <type 'str'>
  23. 23. Class class User: def __init__(self, name): self.name = name def get_name(self): return self.name >>> u = User('smallfish') >>> print u.get_name() smallfish
  24. 24. 模块 # user.py def 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
  25. 25. 列表推导 L ist C omprehension (适用于 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]
  26. 26. 修饰器( 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
  27. 27. 修饰器( 2 ) 测试函数: def hello(n): sum = 0 for i in range(n): sum += I return sum 我们可以这样调用: a = time_wrapper(hello) print a(100) 这个不稀奇,还可以这样写: @time_wrapper def hello(n): … 同上 >>> hello(1000000) hello 0.265000104904
  28. 28. 示例代码( 1 ) <ul><li>交换值 </li></ul><ul><li>1) </li></ul><ul><li>tmp = a </li></ul><ul><li>a = b </li></ul><ul><li>b = tmp </li></ul><ul><li>2) </li></ul><ul><li>a, b = b, a </li></ul><ul><li>判断 key 是否在 dict 中 </li></ul><ul><li>1) </li></ul><ul><li>if d.has_key(key): </li></ul><ul><li>2) </li></ul><ul><li>if key in d: </li></ul>
  29. 29. 示例代码( 2 ) <ul><li>数组转字典 </li></ul><ul><li>name = [&quot;smallfish&quot;, &quot;user_a&quot;, &quot;user_b&quot;] </li></ul><ul><li>city = [&quot;hangzhou&quot;, &quot;nanjing&quot;, &quot;beijing&quot;] </li></ul><ul><li>print dict(zip(name, city)) </li></ul><ul><li>{'user_b': 'beijing', 'user_a': 'nanjing', 'smallfish': 'hangzhou'} </li></ul><ul><li>还需要两次 for 循环么? </li></ul><ul><li>输出文件 </li></ul><ul><li>with open(&quot;d:/1.log&quot;) as fp: </li></ul><ul><li>line = fp.readline() </li></ul><ul><li>print line </li></ul>
  30. 30. 示例代码( 3 ) <ul><li>数据库操作 </li></ul><ul><li>>>> import psycopg2 </li></ul><ul><li>>>> db = psycopg2.connect(&quot;host=localhost user=smallfish password=xx dbname=test&quot;) </li></ul><ul><li>>>> cursor = db.cursor() </li></ul><ul><li>>>> cursor.execute('select version()') </li></ul><ul><li>>>> print cursor.fetchall() </li></ul><ul><li>[('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',)] </li></ul><ul><li>>>> cursor.close() </li></ul><ul><li>>>> db.close() </li></ul>
  31. 31. 其他资源 <ul><li>《 A Byte of Python 》(中文名: Python 简明教程) </li></ul><ul><li>《 Python Tutorial 》( Python 官方手册,必读啊!) </li></ul><ul><li>《 Python Style PEP-0008 》 http://www.python.org/dev/peps/pep-0008/ </li></ul><ul><li>《 Pythonic 》(更多有趣的写法) http://www.slideshare.net/nnfish/pythonic </li></ul>
  32. 32. 结束 print &quot; Thanks! &quot; import sys sys.exit(0)

×