Python最佳实践指南

Python最佳实践指南

  • 英文仓库 https://github.com/realpython/python-guide
  • 中文翻译仓库 https://github.com/prodesire/python-guide-cn/
  • 中文阅读页面 https://pythonguidecn.readthedocs.io/zh/latest/index.html
  • Python入门
  • Python 开发环境
  • 写出优雅的Python代码
    • 代码风格
    • 一般概念
      • 明确的代码
      • 每行一个声明
      • 函数参数
      • 避免魔法方法
      • 我们都是负责任的用户
    • 习语(Idiom)
      • 解包(Unpacking)
      • 创建一个被忽略的变量: 建议使用 “__” 而不是 “_”
      • 创建一个含N个对象的列表 four_nones = [None] * 4
      • 创建一个含N个列表的列表 four_lists = [[] for __ in xrange(4)]
      • 根据列表来创建字符串
        - letters = ['s', 'p', 'a', 'm']
        - word = ''.join(letters)
        
      • 在集合体(collection)中查找一个项 为了性能
    • Python之禅
    • PEP 8
    • 约定
      • 检查变量是否等于常量
        - # 检查值
        - if attr:
            - print 'attr is truthy!'
        - # 或者做相反的检查
        - if not attr:
            - print 'attr is falsey!'
        - # or, since None is considered false, explicitly check for it
        - if attr is None:
            - print 'attr is None!'
        
      • 访问字典元素: 不要使用 dict.has_key() 方法。取而代之,使用 x in d 语法,或者 将一个默认参数传递给 dict.get()。
        - d = {'hello': 'world'}
        - print d.get('hello', 'default_value') # 打印 'world'
        - print d.get('thingy', 'default_value') # 打印 'default_value'
        - # Or:
        - if 'hello' in d:
            - print d['hello']
        
      • 维护列表的捷径
        • 过滤列表
        • 列表与迭代器
        • 修改原始列表可能产生的副作用
        • 在列表中修改值
      • 读取文件 使用 with open 语法来读取文件。它将会为您自动关闭文件。
      • 行的延续 尽量少使用反斜杠,使用()
    • 文档 #

    • 项目文档
    • 项目发布
    • 代码文档建议
      • https://www.python.org/dev/peps/pep-0008/#comments
      • 注释代码块 #
      • 文档字符串 Documentation Strings
          1. 多行文本,结尾的 """ 应该在新行,单行文本,结尾的 """ 保持在本行
        - """Return a foobang
        - Optional plotz says to frobnicate the bizbaz first.
        - """
        
      • 文档字符串 vs 块注释
      • 编写文档字符串
    • 其他工具
  • Python应用的场景指南
  • 部署优雅的Python代码
  • 额外关注