Skip to content

Commit a5cb6a5

Browse files
committed
7.1小节完成
1 parent 21e583a commit a5cb6a5

2 files changed

Lines changed: 68 additions & 9 deletions

File tree

source/c07/p01_functions_that_accept_any_number_arguments.rst

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,74 @@
55
----------
66
问题
77
----------
8-
todo...
8+
你想构造一个可接受任意数量参数的函数。
9+
10+
|
911
1012
----------
1113
解决方案
1214
----------
13-
todo...
15+
为了能让一个函数接受任意数量的位置参数,可以使用一个*参数。例如:
16+
17+
.. code-block:: python
18+
19+
def avg(first, *rest):
20+
return (first + sum(rest)) / (1 + len(rest))
21+
22+
# Sample use
23+
avg(1, 2) # 1.5
24+
avg(1, 2, 3, 4) # 2.5
25+
26+
在这个例子中,rest是由所有其他位置参数组成的元组。然后我们在代码中把它当成了一个序列来进行后续的计算。
27+
28+
为了接受任意数量的关键字参数,使用一个以**开头的参数。比如:
29+
30+
.. code-block:: python
31+
32+
import html
33+
34+
def make_element(name, value, **attrs):
35+
keyvals = [' %s="%s"' % item for item in attrs.items()]
36+
attr_str = ''.join(keyvals)
37+
element = '<{name}{attrs}>{value}</{name}>'.format(
38+
name=name,
39+
attrs=attr_str,
40+
value=html.escape(value))
41+
return element
42+
43+
# Example
44+
# Creates '<item size="large" quantity="6">Albatross</item>'
45+
make_element('item', 'Albatross', size='large', quantity=6)
46+
47+
# Creates '<p>&lt;spam&gt;</p>'
48+
make_element('p', '<spam>')
49+
50+
在这里,attrs是一个包含所有被传入进来的关键字参数的字典。
51+
52+
如果你还希望某个函数能同时接受任意数量的位置参数和关键字参数,可以同时使用*和**。比如:
53+
54+
.. code-block:: python
55+
56+
def anyargs(*args, **kwargs):
57+
print(args) # A tuple
58+
print(kwargs) # A dict
59+
60+
使用这个函数时,所有位置参数会被放到args元组中,所有关键字参数会被放到字典kwargs中。
61+
62+
|
1463
1564
----------
1665
讨论
1766
----------
18-
todo...
67+
一个*参数只能出现在函数定义中最后一个位置参数后面,而 **参数只能出现在最后一个参数。
68+
有一点要注意的是,在*参数后面仍然可以定义其他参数。
69+
70+
.. code-block:: python
71+
72+
def a(x, *args, y):
73+
pass
74+
75+
def b(x, *args, y, **kwargs):
76+
pass
77+
78+
这种参数就是我们所说的仅允许关键字参数,在后面7.2小节还会详细讲解到。

source/chapters/p07_functions.rst

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
第七章:函数
33
=============================
44

5-
Python provides a variety of useful built-in data structures, such as lists, sets, and dictionaries.
6-
For the most part, the use of these structures is straightforward. However,
7-
common questions concerning searching, sorting, ordering, and filtering often arise.
8-
Thus, the goal of this chapter is to discuss common data structures and algorithms
9-
involving data. In addition, treatment is given to the various data structures contained
10-
in the collections module.
5+
使用 ``def`` 语句定义函数是所有程序的基础。
6+
本章的目标是讲解一些更加高级和不常见的函数定义与使用模式。
7+
涉及到的内容包括默认参数、任意数量参数、仅允许关键字参数、注解和闭包。
8+
另外,一些高级的控制流和利用回调函数传递数据的技术在这里也会讲解到。
9+
1110

1211
Contents:
1312

0 commit comments

Comments
 (0)