1)文档字符串出现在函数定义的第一行并且用三引号"""...."""括起来
例如
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.
No, really, it doesn't do anything.
第一行写简介,第二行空行,第三行详细介绍函数调用惯例、副作用等(还可以用来写测试代码)。
docstring测试代码
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)
import doctest
doctest.testmod() # automatically validate the embedded tests
2)函数注释分参数注释(在参数后加 : 定义注释)和返回值注释(参数括号后用 -> 定义注释)
例子
>>> def f(ham: str, eggs: str = 'eggs') -> str:
... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'
3)Package
每个包中除了各种模块定义文件,还要定义一个__init__.py文件,可以在里面定义初始化代码或__all__变量等。__all__变量给出了使用from...import * 时要导入的模块列表。
4)global声明与nonlocal声明
global声明不必绑定变量,在它所在的范围或命名空间(我称之为作用域),可以直接使用该变量(可读可写)。在它的子范围内使用时要重新声明global。
nonlocal 声明要绑定某个局部变量(必须是局部变量,不能是global变量),这个局部变量在离它作用域最近的外面一层作用域(包含了nonlocal 变量的作用域)中。
例子:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam" #无任何声明,故是局部变量
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
输出:
After local assignment: test spam
After nonlocal assignment: nonlocal spam #能改变作用域外最近的那层作用域中的局部变量
After global assignment: nonlocal spam #虽然是global声明,但不改变作用域外的非global声明的变量
In global scope: global spam