Skip to content

Commit 4ee0547

Browse files
committed
7.3小节完成
1 parent 279e51e commit 4ee0547

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

cookbook/c07/p03_func_annotate.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Topic: 函数注解元信息
5+
Desc :
6+
"""
7+
8+
def add(x:int, y:int) -> int:
9+
return x + y
10+
11+
help(add)
12+
13+
print(add.__annotations__)
14+

source/c07/p03_attach_informatinal_matadata_to_function_arguments.rst

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,47 @@
55
----------
66
问题
77
----------
8-
todo...
8+
你写好了一个函数,然后想为这个函数的参数增加一些额外的信息,这样的话其他使用者就能清楚的知道这个函数应该怎么使用。
9+
10+
|
911
1012
----------
1113
解决方案
1214
----------
13-
todo...
15+
使用函数参数注解是一个很好的办法,它能提示程序员应该怎样正确使用这个函数。
16+
例如,下面有一个被注解了的函数:
17+
18+
.. code-block:: python
19+
20+
def add(x:int, y:int) -> int:
21+
return x + y
22+
23+
python解释器不会对这些注解添加任何的语义。它们不会被类型检查,运行时跟没有加注解之前的效果也没有任何差距。
24+
然而,对于那些阅读源码的人来讲就很有帮助啦。第三方工具和框架可能会对这些注解添加语义。同时它们也会出现在文档中。
25+
26+
.. code-block:: python
27+
28+
>>> help(add)
29+
Help on function add in module __main__:
30+
add(x: int, y: int) -> int
31+
>>>
32+
33+
尽管你可以使用任意类型的对象给函数添加注解(例如数字,字符串,对象实例等等),不过通常来讲使用类或着字符串会比较好点。
34+
35+
|
1436
1537
----------
1638
讨论
1739
----------
18-
todo...
40+
函数注解只存储在函数的 ``__annotations__`` 属性中。例如:
41+
42+
.. code-block:: python
43+
44+
>>> add.__annotations__
45+
{'y': <class 'int'>, 'return': <class 'int'>, 'x': <class 'int'>}
46+
47+
尽管注解的使用方法可能有很多种,但是它们的主要用途还是文档。
48+
因为python并没有类型声明,通常来讲仅仅通过阅读源码很难知道应该传递什么样的参数给这个函数。
49+
这时候使用注解就能给程序员更多的提示,让他们可以争取的使用函数。
50+
51+
参考9.20小节的一个更加高级的例子,演示了如何利用注解来实现多分派(比如重载函数)。

0 commit comments

Comments
 (0)