Section 114.1: 字典键初始化

如果不确定键是否存在,建议使用 dict.get 方法。如果键不存在,它允许你返回一个默认值。传统的 dict[key] 方法会引发 KeyError 异常。

与其写:

def add_student():
  try:
    students['count'] += 1
  except KeyError:
    students['count'] = 1

不如写:

def add_student():
  students['count'] = students.get('count', 0) + 1

Section 114.2: 交换变量

要交换两个变量的值,可以使用元组解包。

>>> x = True
>>> y = False
>>> x, y = y, x
>>> x
False
>>> y
True

交换变量

Section 114.3: 使用真值测试

Python 会隐式地将任何对象转换为布尔值进行测试,因此尽可能使用它。

# 好例子,使用隐式真值测试
if attr:
  # do something

if not attr:
  # do something

# 坏例子,使用特定类型
if attr == 1:
  # do something

if attr == True:
  # do something

if attr != '':
  # do something

# 如果你想专门检查是否为 None,使用 'is' 或 'is not'
if attr is None:
  # do something

这通常会产生更易读的代码,并且在处理意外类型时通常更安全。

点击此处查看哪些值会被评估为 False。

Section 114.4: 测试 __main__ 以避免意外代码执行

在执行代码之前,测试调用程序的 __name__ 变量是一个好习惯。

import sys

def main():
  # 你的代码从这里开始

  # 别忘了提供返回码
  return 0

if __name__ == "__main__":
  sys.exit(main())

使用这种模式可以确保你的代码只在你期望的时候执行;例如,当你显式运行你的文件时:

python my_program.py

然而,好处在于,如果你决定在另一个程序中导入你的文件(例如,如果你正在编写一个库的一部分),你可以导入你的文件,而 __main__ 陷阱将确保不会意外执行任何代码:

# 一个新程序文件
import my_program # main() 不会运行

# 但如果你真的想运行它,你可以显式调用 main():
my_program.main()