Effective Python
本章节作为<<Effective Python 编写高质量Python代码的59个有效方法>>读书笔记
用Pythonic方式来思考
第1条:确认自己所用的Python版本
python --version
import sys
sys.version # str
sys.version_info # object
第2条:遵循 PEP 8 风格指南
PEP 8 针对Python代码格式而编订的风格指南,以便在阅读代码时可以根据这些名称看出它们在Python语言中的角色
函数、变量及属性应该用小写字母来拼写,各单词之间以下划线相连,如 lowercase_underscore
受保护的实例属性,应该以单个下划线开头,如 _leading_underscore
私有的实例属性,应该以两个下划线开头,如 __double_leading_underscore
类与异常,应该以每个单词首字母大写的形式来命名,如 CapitalizedWord
模块级别的常量,应该全部采用大写字母来拼写,各单词之间以下划线相连,如 ALL_CAPS
类中的实例方法(instance method),应该把首个参数命名为self,以表示该对象值
类方法(class method)的首个参数,应该命名为cls,以表示该类自身
文件中的那些 import 语句,总是应该使用绝对导入,可分为三部分
标准库
第三方模块
自用模块
第3条:了解 bytes、str 与 unicode 的区别
由于字符类型有区别,Python代码中经常会出现两种常见的使用情境
开发者需要原始8位字节值,通常以utf-8(或其他编码形式)来编码的字符
开发者需要操作没有特定编码形式的Unicode字符
# coding:utf-8
import six
def to_unicode(s, encoding='utf-8', errors='strict'):
if six.PY2:
return s if isinstance(s, unicode)\
else s.decode(encoding, errors=errors)
else:
return s if isinstance(s, six.string_types)\
else s.decode(encoding, errors=errors)
def to_byte(s, encoding='utf-8', errors='strict'):
if six.PY2:
return s.encode(encoding, errors=errors)\
if isinstance(s, unicode) else s
else:
return s.encode(encoding, errors=errors)\
if isinstance(s, six.string_types) else s
第 4 条:用辅助函数来取代复杂的表达式
from urllib.parse import parse_qs
my_values = parse_qs('red=5&blue=0&green=', keep_blank_values=True)
print(my_values) # {'red': ['5'], 'blue': ['0'], 'green': ['']}
def get_first_int(values, key, default=0):
found = values.get(key, [''])
if found[0]:
found = int(found[0])
else:
found = default
return found
print(get_first_int(my_values, 'green'))
第 5 条:了解切割序列的办法
函数
第14条:尽量用异常来表示特殊情况,而不要返回None
Last updated