From f80c9800fc5f9652e13f31f7bcb65bb39ca325ed Mon Sep 17 00:00:00 2001 From: dongjingxiang <534458392@qq.com> Date: Mon, 28 Jun 2021 20:06:49 +0800 Subject: [PATCH 1/8] =?UTF-8?q?=E7=BF=BB=E8=AF=91=E5=AD=A6=E4=B9=A0Python?= =?UTF-8?q?=20=E4=B8=AD=E6=96=87=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.zh-CN.md | 203 ++++++++++++++++++++++++++ src/control_flow/test_for.py | 20 +-- src/data_types/test_numbers.py | 48 +++--- src/data_types/test_strings.py | 72 ++++----- src/getting_started/python_syntax.md | 38 +++-- src/getting_started/test_variables.py | 34 ++--- src/getting_started/what_is_python.md | 46 +++--- src/operators/test_arithmetic.py | 22 +-- src/operators/test_assigment.py | 42 +++--- src/operators/test_bitwise.py | 33 ++--- src/operators/test_comparison.py | 16 +- src/operators/test_identity.py | 22 ++- src/operators/test_logical.py | 14 +- src/operators/test_membership.py | 16 +- 14 files changed, 403 insertions(+), 223 deletions(-) create mode 100644 README.zh-CN.md diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 00000000..672e0868 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,203 @@ +# 学习 Python 的游乐场(playground)和备忘单(cheatsheet) + +[](https://travis-ci.org/trekhleb/learn-python) + +> 这是 Python 脚本的集合,按 [主题](目录)划分,包含带有解释的代码示例、不同的用例和进一步阅读的链接。 + +_Read this in_ [_Português_](README.pt-BR.md). + +这是一个**游乐场(playground)**,因为您可以更改或添加代码以查看它是如何工作的, +并使用断言 [测试代码](#testing-the-code)。它还允许您 [lint the code](#linting-the-code) +并检查它是否符合 Python 代码风格指南。 +总而言之,它可能会使您的学习过程更具交互性,并且可能会帮助您从一开始就保持较高的代码质量。 + +这是一个**备忘单(cheatsheet)**,因为一旦您想回顾[标准 Python 语句和结构](#table-of-contents)的语法,您可能会回到这些代码示例。 +此外,由于代码中充满了断言,您无需启动它们就可以立即看到预期的函数语句输出。 + +> _你可能也对🤖感兴趣 [交互式机器学习实验](https://github.com/trekhleb/machine-learning-experiments)_ + +## 如何使用此存储库 + +此存储库中的每个 Python 脚本都具有以下结构: + +```python +"""Lists <--- 这里的主题名称 + +# @see: https://www.learnpython.org/en/Lists <-- 进一步阅读的链接在这里 + +这里可能会对当前主题进行更详细的解释(即关于列表的一般信息)。 +""" + + +def test_list_type(): + """ + 子主题的解释在这里。每个文件都包含说明子主题的测试函数(即列表类型、列表方法)。 + """ + + # 以下是如何构建列表的示例。 <-- 这里的评论解释了这个动作 + squares = [1, 4, 9, 16, 25] + + # 列表可以被索引和切片。 + # 索引返回项目。 + assert squares[0] == 1 # <-- 这里的断言说明了结果。 + # 切片返回一个新列表。 + assert squares[-3:] == [9, 16, 25] # <-- 这里的断言说明了结果。 +``` + +所以通常你可能想要执行以下操作: + +- [Find the topic](#table-of-contents)你想学习或回顾。 +- 阅读每个脚本的文档字符串中链接的注释和/或文档(如上例所示)。 +- 查看代码示例和断言以查看使用示例和预期输出。 +- 更改代码或添加新断言以查看工作方式。 +- [Run tests](#testing-the-code) and [lint the code](#linting-the-code) 看看它是否有效并且是否正确写入。 + +## 目录 + +1. **入门** + - [什么是 Python](src/getting_started/what_is_python.md) + - [Python 语法](src/getting_started/python_syntax.md) + - [变量](src/getting_started/test_variables.py) +2. **运算符** + - [算术运算符](src/operators/test_arithmetic.py) (`+`, `-`, `*`, `/`, `//`, `%`, `**`) + - [位运算符](src/operators/test_bitwise.py) (`&`, `|`, `^`, `>>`, `<<`, `~`) + - [赋值运算符](src/operators/test_assigment.py) (`=`, `+=`, `-=`, `/=`, `//=` etc.) + - [比较运算符](src/operators/test_comparison.py) (`==`, `!=`, `>`, `<`, `>=`, `<=`) + - [逻辑运算符](src/operators/test_logical.py) (`and`, `or`, `not`) + - [恒等运算符](src/operators/test_identity.py) (`is`, `is not`) + - [成员运算符](src/operators/test_membership.py) (`in`, `not in`) +3. **数据类型** + - [数字](src/data_types/test_numbers.py) (其中包括布尔值) + - [字符串](src/data_types/test_strings.py) 以及方法 + - [列表](src/data_types/test_lists.py) 以及方法(包括列表推导式) + - [元组](src/data_types/test_tuples.py) + - [集合](src/data_types/test_sets.py)及其方法 + - [字典](src/data_types/test_dictionaries.py) + - [Type Casting](src/data_types/test_type_casting.py) +4. **控制** + - [if](src/control_flow/test_if.py) + - [for](src/control_flow/test_for.py) (以及 `range()` 函数) + - [while](src/control_flow/test_while.py) + - [try](src/control_flow/test_try.py) + - [break](src/control_flow/test_break.py) + - [continue](src/control_flow/test_continue.py) +5. **函数** + - [函数定义](src/functions/test_function_definition.py) (`def` and `return` statements) + - [函数内部变量的作用域](src/functions/test_function_scopes.py) (`global` and `nonlocal` statements) + - [默认参数值](src/functions/test_function_default_arguments.py) + - [关键字参数](src/functions/test_function_keyword_arguments.py) + - [任意的参数列表](src/functions/test_function_arbitrary_arguments.py) + - [拆包参数列表](src/functions/test_function_unpacking_arguments.py) (`*` and `**` statements) + - [Lambda表达式](src/functions/test_lambda_expressions.py) (`lambda` statement) + - [文档字符串](src/functions/test_function_documentation_string.py) + - [函数注释](src/functions/test_function_annotations.py) + - [函数修饰符](src/functions/test_function_decorators.py) +6. **类** + - [类定义](src/classes/test_class_definition.py) (`class` statement) + - [类对象](src/classes/test_class_objects.py) + - [实例对象](src/classes/test_instance_objects.py) + - [方法对象](src/classes/test_method_objects.py) + - [类和实例变量](src/classes/test_class_and_instance_variables.py) + - [继承](src/classes/test_inheritance.py) + - [多重继承](src/classes/test_multiple_inheritance.py) +7. **组件** + - [组件](src/modules/test_modules.py) (`import` statement) + - [包](src/modules/test_packages.py) +8. **错误和异常** + - [处理异常](src/exceptions/test_handle_exceptions.py) (`try` statement) + - [提高异常](src/exceptions/test_raise_exceptions.py) (`raise` statement) +9. **文件** + - [读与写](src/files/test_file_reading.py) (`with` statement) + - [文件对象的方法](src/files/test_file_methods.py) +10. **附加物** + - [`pass` 声明](src/additions/test_pass.py) + - [生成器](src/additions/test_generators.py) (`yield` 声明) +11. **标准库简介** + - [序列化](src/standard_libraries/test_json.py) (`json` library) + - [文件通配符](src/standard_libraries/test_glob.py) (`glob` library) + - [字符串匹配](src/standard_libraries/test_re.py) (`re` library) + - [数学运算](src/standard_libraries/test_math.py) (`math`, `random`, `statistics` libraries) + - [日期和时间](src/standard_libraries/test_datetime.py) (`datetime` library) + - [数据压缩](src/standard_libraries/test_zlib.py) (`zlib` library) + +## 预备知识 + +**安装Python** + +确保你安装了[Python3](https://realpython.com/installing-python/) on your machine. + +你可能想要使用[venv](https://docs.python.org/3/library/venv.html)标准Python库 +创建虚拟环境并安装Python、pip和所有依赖包从本地项目目录提供,以避免与系统范围的包及其版本。 + +根据你的安装,你可以通过运行`python` 或 `python3`。pip包管理器也是如此——它也可能是可访问的 +通过运行 `pip `或` pip3 `。 + +You may check your Python version by running: + +```bash +python --version +``` + +Note that in this repository whenever you see `python` it will be assumed that it is Python **3**. + +**Installing dependencies** + +Install all dependencies that are required for the project by running: + +```bash +pip install -r requirements.txt +``` + +## 测试代码 + +测试使用 [pytest](https://docs.pytest.org/en/latest/) 框架. + +您可以通过 `test_` 作为前缀添加文件和函数为自己添加新的测试 +(例如: 在 `test_topic.py` 里添加 `def test_sub_topic()` 函数). + +要运行所有测试,请从项目根文件夹执行以下命令: + +```bash +pytest +``` + +要运行特定的测试,请执行: + +```bash +pytest ./path/to/the/test_file.py +``` + +## 代码检测 + +代码检测用的是 [pylint](http://pylint.pycqa.org/) 和 [flake8](http://flake8.pycqa.org/en/latest/) 库. + +### PyLint + +来检查代码是否按 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 规定编写,请执行: + +```bash +pylint ./src/ +``` + +以防linter检测到错误 (i.e. `missing-docstring`) 你可能想读更多关于 +具体运行错误: + +```bash +pylint --help-msg=missing-docstring +``` + +[More about PyLint](http://pylint.pycqa.org/) + +### Flake8 + +来检查代码是否按 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 规定编写,请执行: + +```bash +flake8 ./src +``` + +或者,如果你想有更详细的输出,你可以运行: + +```bash +flake8 ./src --statistics --show-source --count +``` diff --git a/src/control_flow/test_for.py b/src/control_flow/test_for.py index 7411277b..3c830d7f 100644 --- a/src/control_flow/test_for.py +++ b/src/control_flow/test_for.py @@ -2,28 +2,26 @@ @see: https://docs.python.org/3/tutorial/controlflow.html -The for statement in Python differs a bit from what you may be used to in C or Pascal. -Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or -giving the user the ability to define both the iteration step and halting condition (as C), -Python’s for statement iterates over the items of any sequence (a list or a string), in the -order that they appear in the sequence. For example (no pun intended): +Python 中的 for 语句与您可能在 C 或 Pascal 中使用的语句略有不同。 +Python 的 for 语句不是总是迭代数字的等差数列(如在 Pascal 中),也不是让用户能够定义迭代步骤和暂停条件(如 C), +而是迭代任何序列(列表或一个字符串),按照它们在序列中出现的顺序。例如(没有双关语意): """ # pylint: disable=too-many-locals def test_for_statement(): - """FOR statement""" + """FOR 语句""" - # Measure some strings: + # 测试一些字符串: words = ['cat', 'window', 'defenestrate'] words_length = 0 for word in words: words_length += len(word) - # "cat" length is 3 - # "window" length is 6 - # "defenestrate" length is 12 + # "cat" 长度是 3 + # "window" 长度是 6 + # "defenestrate" 长度是 12 assert words_length == (3 + 6 + 12) # If you need to modify the sequence you are iterating over while inside the loop @@ -34,6 +32,8 @@ def test_for_statement(): if len(word) > 6: words.insert(0, word) + print(words) + # Otherwise with for w in words:, the example would attempt to create an infinite list, # inserting defenestrate over and over again. diff --git a/src/data_types/test_numbers.py b/src/data_types/test_numbers.py index 66bb111c..ae579cda 100644 --- a/src/data_types/test_numbers.py +++ b/src/data_types/test_numbers.py @@ -1,9 +1,9 @@ -"""Numbers. +"""数字. @see: https://docs.python.org/3/tutorial/introduction.html @see: https://www.w3schools.com/python/python_numbers.asp -There are three numeric types in Python: +Python中有三种数值类型: - int (e.g. 2, 4, 20) - bool (e.g. False and True, acting like 0 and 1) - float (e.g. 5.0, 1.6) @@ -14,8 +14,7 @@ def test_integer_numbers(): """Integer type - Int, or integer, is a whole number, positive or negative, - without decimals, of unlimited length. + Int或integer是一个整数,无论正或负,没有小数,无限长. """ positive_integer = 1 @@ -30,11 +29,9 @@ def test_integer_numbers(): def test_booleans(): """Boolean - Booleans represent the truth values False and True. The two objects representing the values - False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, - and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the - exception being that when converted to a string, the strings "False" or "True" are returned, - respectively. + 布尔值表示真值False和True。表示值的两个对象False和True是唯一的布尔对象。 + 布尔类型是整数类型的子类型,和布尔值的行为类似于值0和1,在几乎所有上下文中 + 例外是当转换为字符串时,返回字符串"False"或"True" """ true_boolean = True @@ -46,7 +43,7 @@ def test_booleans(): assert isinstance(true_boolean, bool) assert isinstance(false_boolean, bool) - # Let's try to cast boolean to string. + # 让我们尝试将布尔类型转换为字符串。 assert str(true_boolean) == "True" assert str(false_boolean) == "False" @@ -54,12 +51,11 @@ def test_booleans(): def test_float_numbers(): """Float type - Float, or "floating point number" is a number, positive or negative, - containing one or more decimals. + 浮点数,或“浮点数”是一个数,无论正或负,包含一个或多个小数的 """ float_number = 7.0 - # Another way of declaring float is using float() function. + # 另一种声明浮点数的方法是使用float()函数。 float_number_via_function = float(7) float_negative = -35.59 @@ -68,8 +64,7 @@ def test_float_numbers(): assert isinstance(float_number_via_function, float) assert isinstance(float_negative, float) - # Float can also be scientific numbers with an "e" to indicate - # the power of 10. + # Float也可以是用“e”表示的科学数字 10 的幂。 float_with_small_e = 35e3 float_with_big_e = 12E4 @@ -80,7 +75,7 @@ def test_float_numbers(): def test_complex_numbers(): - """Complex Type""" + """复数型""" complex_number_1 = 5 + 6j complex_number_2 = 3 - 2j @@ -91,30 +86,29 @@ def test_complex_numbers(): def test_number_operators(): - """Basic operations""" + """ 基本运算""" - # Addition. + # 加法. assert 2 + 4 == 6 - # Multiplication. + # 乘法. assert 2 * 4 == 8 - # Division always returns a floating point number. + # 除法总是返回浮点数. assert 12 / 3 == 4.0 assert 12 / 5 == 2.4 assert 17 / 3 == 5.666666666666667 - # Modulo operator returns the remainder of the division. + # 取模运算符返回除法的余数. assert 12 % 3 == 0 assert 13 % 3 == 1 - # Floor division discards the fractional part. + # 除法向下取整摒弃了小数部分. assert 17 // 3 == 5 - # Raising the number to specific power. - assert 5 ** 2 == 25 # 5 squared - assert 2 ** 7 == 128 # 2 to the power of 7 + # 把数字提高到特定的幂。 + assert 5 ** 2 == 25 # 5的平方 + assert 2 ** 7 == 128 # 2的7次方 - # There is full support for floating point; operators with - # mixed type operands convert the integer operand to floating point. + # 运算符与混合类型操作数将整数操作数转换为浮点数。 assert 4 * 3.75 - 1 == 14.0 diff --git a/src/data_types/test_strings.py b/src/data_types/test_strings.py index ae86432f..88dd708c 100644 --- a/src/data_types/test_strings.py +++ b/src/data_types/test_strings.py @@ -1,77 +1,69 @@ -"""Strings. +"""字符串. @see: https://docs.python.org/3/tutorial/introduction.html @see: https://www.w3schools.com/python/python_strings.asp @see: https://www.w3schools.com/python/python_ref_string.asp -Besides numbers, Python can also manipulate strings, which can be -expressed in several ways. They can be enclosed in single quotes ('...') -or double quotes ("...") with the same result. +除了数字,Python还可以操作字符串,可以是 +用几种方式表达。它们可以用单引号括起来('…') +或者双引号(“…”),结果相同。 """ import pytest def test_string_type(): - """String type""" + """字符串类型""" - # String with double quotes. + # 双引号字符串。 name_1 = "John" - # String with single quotes. + # 带有单引号的字符串。 name_2 = 'John' - # Strings created with different kind of quotes are treated the same. + # 使用不同类型的引号创建的字符串被视为相同的。 assert name_1 == name_2 assert isinstance(name_1, str) assert isinstance(name_2, str) - # \ can be used to escape quotes. - # use \' to escape the single quote or use double quotes instead. + # \ 可以用来转义引号。 + # 使用\'转义单引号或使用双引号代替。 single_quote_string = 'doesn\'t' double_quote_string = "doesn't" assert single_quote_string == double_quote_string - # \n means newline. + # \ n表示换行符。 multiline_string = 'First line.\nSecond line.' - # Without print(), \n is included in the output. - # But with print(), \n produces a new line. + # 如果没有print(),输出中将包含\n。 + # 但是使用print(), \n会产生一个新行。 assert multiline_string == 'First line.\nSecond line.' - # Strings can be indexed, with the first character having index 0. - # There is no separate character type; a character is simply a string - # of size one. Note that since -0 is the same as 0, negative indices - # start from -1. + # 字符串可以被索引,第一个字符的索引为0。 + # 没有单独的字符类型;一个字符就是一个字符串的大小。请注意,因为-0和0是相同的,所以负索引从1开始。 word = 'Python' - assert word[0] == 'P' # First character. - assert word[5] == 'n' # Fifth character. - assert word[-1] == 'n' # Last character. - assert word[-2] == 'o' # Second-last character. - assert word[-6] == 'P' # Sixth from the end or zeroth from the beginning. + assert word[0] == 'P' # 首位字符 + assert word[5] == 'n' # 第 6个字符。 + assert word[-1] == 'n' # 最后一个字符. + assert word[-2] == 'o' # 倒数第二个的字符。 + assert word[-6] == 'P' # 倒数第六个 或 正数第1个字符. assert isinstance(word[0], str) - # In addition to indexing, slicing is also supported. While indexing is - # used to obtain individual characters, slicing allows you to obtain - # substring: - assert word[0:2] == 'Py' # Characters from position 0 (included) to 2 (excluded). - assert word[2:5] == 'tho' # Characters from position 2 (included) to 5 (excluded). + # 除了索引之外,还支持切片. 虽然索引用来获取个别字符,切片可以让您获取子字符串: + assert word[0:2] == 'Py' # 从位置0(包括)到位置2(不包括)的字符. + assert word[2:5] == 'tho' # 位置2(包括)至位置5(不包括)的字符. - # Note how the start is always included, and the end always excluded. - # This makes sure that s[:i] + s[i:] is always equal to s: + # 注意开头总是包含在内,而结尾总是被排除在外. + # 这确保了s[:i] + s[i:]总是等于s: assert word[:2] + word[2:] == 'Python' assert word[:4] + word[4:] == 'Python' - # Slice indices have useful defaults; an omitted first index defaults to - # zero, an omitted second index defaults to the size of the string being - # sliced. - assert word[:2] == 'Py' # Character from the beginning to position 2 (excluded). - assert word[4:] == 'on' # Characters from position 4 (included) to the end. - assert word[-2:] == 'on' # Characters from the second-last (included) to the end. - - # One way to remember how slices work is to think of the indices as - # pointing between characters, with the left edge of the first character - # numbered 0. Then the right edge of the last character of a string of n - # characters has index n, for example: + # 切片索引具有有用的缺省值; 省略的第一个索引默认为0,被省略的第二索引默认为字符串的大小切片. + assert word[:2] == 'Py' # 字符从开始到位置2(不包括). + assert word[4:] == 'on' # 从位置4(包括)到末尾的字符. + assert word[-2:] == 'on' # 字符从倒数第二(包括)到结尾. + + # 记住切片是如何工作的一种方法是把指标看作指向字符之间的,具有第一个字符的左边缘的 + # 编号0. 然后是字符串n的最后一个字符的右边缘例如,字符的索引为n: # # +---+---+---+---+---+---+ # | P | y | t | h | o | n | diff --git a/src/getting_started/python_syntax.md b/src/getting_started/python_syntax.md index 62dd5be7..6aaf39a9 100644 --- a/src/getting_started/python_syntax.md +++ b/src/getting_started/python_syntax.md @@ -1,49 +1,45 @@ -# Python Syntax +# Python语法 -**Python Syntax compared to other programming languages** +**与其他编程语言相比的Python语法** -- Python was designed to for readability, and has some similarities to the English language with influence from mathematics. -- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. -- Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. +- Python是为可读性而设计的,受数学影响,和英语有一些相似之处。 +- Python使用新行来完成命令,而其他编程语言通常使用分号或括号。 +- Python依赖缩进,使用空格来定义作用域;如循环、函数和类的作用域。其他编程语言经常为此使用大括号。 +## Python 缩进 -## Python Indentations - -Where in other programming languages the indentation in code is for readability only, in Python the indentation is very important. - -Python uses indentation to indicate a block of code. +在其他编程语言中,代码的缩进只是为了可读性,而在Python中缩进是非常重要的。 +Python使用缩进来表示代码块。 ```python if 5 > 2: print("Five is greater than two!") ``` -Python will give you an error if you skip the indentation. +如果你跳过缩进,Python会给你一个错误。 -## Comments +## 注释 -Python has commenting capability for the purpose of in-code documentation. - -Comments start with a `#`, and Python will render the rest of the line as a comment: +Python具有注释功能,用于代码内文档。 +注释以' '开头,Python会将该行的其余部分呈现为注释: ```python #This is a comment. print("Hello, World!") ``` -## Docstrings - -Python also has extended documentation capability, called docstrings. +## 文档注释 -Docstrings can be one line, or multiline. Docstrings are also comments: +Python还具有扩展的文档功能,称为文档字符串。 -Python uses triple quotes at the beginning and end of the docstring: +文档字符串可以是一行或多行。文档字符串也是注释: +Python在文档字符串的开头和结尾使用了三引号: ```python """This is a multiline docstring.""" print("Hello, World!") ``` -## References +## 参考 - [w3schools.com](https://www.w3schools.com/python/python_syntax.asp) diff --git a/src/getting_started/test_variables.py b/src/getting_started/test_variables.py index d41e777a..8bf6d711 100644 --- a/src/getting_started/test_variables.py +++ b/src/getting_started/test_variables.py @@ -1,30 +1,30 @@ -"""Variables +""" 变量 @see: https://docs.python.org/3/tutorial/introduction.html @see: https://www.w3schools.com/python/python_variables.asp @see: https://www.learnpython.org/en/Variables_and_Types -Python is completely object oriented, and not "statically typed". -You do not need to declare variables before using them, or declare -their type. Every variable in Python is an object. +Python是完全面向对象的,而不是“静态类型的”。 +在使用变量之前不需要声明变量,也不需要声明变量类型。 +Python中的每个变量都是一个对象。 -Unlike other programming languages, Python has no command for -declaring a variable. A variable is created the moment you first assign -a value to it. +与其他编程语言不同,Python没有命令 +声明一个变量。变量在您第一次赋值时就被创建 +一个值。 -A variable can have a short name (like x and y) or a more descriptive name -(age, carname, total_volume). +变量可以有一个较短的名称(如x和y)或更具描述性的名称 +(年龄、carname total_volume)。 -Rules for Python variables: -- A variable name must start with a letter or the underscore character. -- A variable name cannot start with a number. -- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). -- Variable names are case-sensitive (age, Age and AGE are three different variables). +Python变量的规则: +— 变量名必须以字母或下划线开头。 +— 变量名不能以数字开头。 +— 只能包含字母数字和下划线(A-z、0-9、_)。 +- 变量名区分大小写(age, age和age是三个不同的变量)。 """ def test_variables(): - """Test variables""" + """测试变量""" integer_variable = 5 string_variable = 'John' @@ -32,7 +32,7 @@ def test_variables(): assert integer_variable == 5 assert string_variable == 'John' - variable_with_changed_type = 4 # x is of type int - variable_with_changed_type = 'Sally' # x is now of type str + variable_with_changed_type = 4 # x 的类型是 int + variable_with_changed_type = 'Sally' # x 现在的类型是 str assert variable_with_changed_type == 'Sally' diff --git a/src/getting_started/what_is_python.md b/src/getting_started/what_is_python.md index 391327e9..f7db1673 100644 --- a/src/getting_started/what_is_python.md +++ b/src/getting_started/what_is_python.md @@ -1,37 +1,35 @@ -# What is Python +# 什么是 Python -Python is a popular programming language. It was created in 1991 by Guido van Rossum. +Python是一种流行的编程语言。它是由Guido van Rossum在1991年创建的。 -Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. +Python是一种易于学习、功能强大的编程语言。它具有高效的高级数据结构和简单但有效的面向对象编程方法。Python优雅的语法和动态类型,加上它的解释性质,使它成为大多数平台上许多领域的脚本编写和快速应用程序开发的理想语言。 -It is used for: +它用于: -- web development (server-side), -- software development, -- mathematics, -- system scripting. +- web开发(服务器端), +- 软件开发, +- 数学 +- 系统脚本。 -## What can Python do? +## Python能做什么? -- Python can be used on a server to create web applications. -- Python can be used alongside software to create workflows. -- Python can connect to database systems. It can also read and modify files. -- Python can be used to handle big data and perform complex mathematics. -- Python can be used for rapid prototyping, or for production-ready software development. +- Python可以在服务器上创建web应用。 +- Python可以与软件一起使用来创建工作流。 +- Python可以连接数据库系统。它还可以读取和修改文件。 +- Python可以用来处理大数据和执行复杂的数学。 +- Python可用于快速原型,或用于生产就绪软件开发。 -## Why Python? - -- Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). -- Python has a simple syntax similar to the English language. -- Python has syntax that allows developers to write programs with fewer lines than some other programming languages. -- Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. -- Python can be treated in a procedural way, an object-orientated way or a functional way. +## 为什么选择 Python ? +- Python可以在不同的平台上工作(Windows, Mac, Linux,树莓派等)。 +- Python具有类似于英语的简单语法。 +- Python的语法允许开发者用比其他编程语言更少的行来编写程序。 +- Python运行在解释器系统上,这意味着代码一旦写好就可以被执行。这意味着原型制作可以非常快速。 +- Python可以以过程方式、面向对象方式或函数方式来处理。 ## Good to know -- The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular. -- In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files. - +- Python最新的主要版本是Python 3,我们将在本教程中使用它。然而,Python 2,尽管除了安全更新之外没有任何更新,但仍然相当流行。 +- 在本教程中,Python将使用文本编辑器编写。可以在集成开发环境中编写Python,如thony、Pycharm、Netbeans或Eclipse,这些在管理更大的Python文件集合时特别有用。 ## References - [w3schools.com](https://www.w3schools.com/python/python_intro.asp) \ No newline at end of file diff --git a/src/operators/test_arithmetic.py b/src/operators/test_arithmetic.py index fa66ad66..b590243e 100644 --- a/src/operators/test_arithmetic.py +++ b/src/operators/test_arithmetic.py @@ -1,42 +1,42 @@ -"""Arithmetic operators +"""算术运算符 @see: https://www.w3schools.com/python/python_operators.asp -Arithmetic operators are used with numeric values to perform common mathematical operations +算术运算符用于数值来执行常见的数学运算 """ def test_arithmetic_operators(): - """Arithmetic operators""" + """算术运算符""" - # Addition. + # 加. assert 5 + 3 == 8 - # Subtraction. + # 减. assert 5 - 3 == 2 - # Multiplication. + # 乘. assert 5 * 3 == 15 assert isinstance(5 * 3, int) - # Division. - # Result of division is float number. + # 除. + # 除法的结果是浮点数. assert 5 / 3 == 1.6666666666666667 assert 8 / 4 == 2 assert isinstance(5 / 3, float) assert isinstance(8 / 4, float) - # Modulus. + # 模运算. assert 5 % 3 == 2 - # Exponentiation. + # 取幂. assert 5 ** 3 == 125 assert 2 ** 3 == 8 assert 2 ** 4 == 16 assert 2 ** 5 == 32 assert isinstance(5 ** 3, int) - # Floor division. + # 向下取整除数. assert 5 // 3 == 1 assert 6 // 3 == 2 assert 7 // 3 == 2 diff --git a/src/operators/test_assigment.py b/src/operators/test_assigment.py index dedfca47..c5a9e120 100644 --- a/src/operators/test_assigment.py +++ b/src/operators/test_assigment.py @@ -1,94 +1,94 @@ -"""Assignment operators +"""赋值运算符 @see: https://www.w3schools.com/python/python_operators.asp -Assignment operators are used to assign values to variables +赋值运算符用于给变量赋值 """ def test_assignment_operator(): - """Assignment operator """ + """ 赋值运算符 """ - # Assignment: = + # 赋值: = number = 5 assert number == 5 - # Multiple assignment. - # The variables first_variable and second_variable simultaneously get the new values 0 and 1. + # 多重赋值. + # 变量first_variable和second_variable同时得到新的值0和1。 first_variable, second_variable = 0, 1 assert first_variable == 0 assert second_variable == 1 - # You may even switch variable values using multiple assignment. + # 您甚至可以使用多次赋值来切换变量值。 first_variable, second_variable = second_variable, first_variable assert first_variable == 1 assert second_variable == 0 def test_augmented_assignment_operators(): - """Assignment operator combined with arithmetic and bitwise operators""" + """赋值操作符结合算术操作符和位操作符""" - # Assignment: += + # 赋值: += number = 5 number += 3 assert number == 8 - # Assignment: -= + # 赋值: -= number = 5 number -= 3 assert number == 2 - # Assignment: *= + # 赋值: *= number = 5 number *= 3 assert number == 15 - # Assignment: /= + # 赋值: /= number = 8 number /= 4 assert number == 2 - # Assignment: %= + # 赋值: %= number = 8 number %= 3 assert number == 2 - # Assignment: %= + # 赋值: %= number = 5 number %= 3 assert number == 2 - # Assignment: //= + # 赋值: //= number = 5 number //= 3 assert number == 1 - # Assignment: **= + # 赋值: **= number = 5 number **= 3 assert number == 125 - # Assignment: &= + # 赋值: &= number = 5 # 0b0101 number &= 3 # 0b0011 assert number == 1 # 0b0001 - # Assignment: |= + # 赋值: |= number = 5 # 0b0101 number |= 3 # 0b0011 assert number == 7 # 0b0111 - # Assignment: ^= + # 赋值: ^= number = 5 # 0b0101 number ^= 3 # 0b0011 assert number == 6 # 0b0110 - # Assignment: >>= + # 赋值: >>= number = 5 number >>= 3 assert number == 0 # (((5 // 2) // 2) // 2) - # Assignment: <<= + # 赋值: <<= number = 5 number <<= 3 assert number == 40 # 5 * 2 * 2 * 2 diff --git a/src/operators/test_bitwise.py b/src/operators/test_bitwise.py index 20118a16..83af0bfb 100644 --- a/src/operators/test_bitwise.py +++ b/src/operators/test_bitwise.py @@ -1,55 +1,54 @@ -"""Bitwise operators +"""位运算符 @see: https://www.w3schools.com/python/python_operators.asp -Bitwise operators manipulate numbers on bit level. +位运算符在位级上操作数字。 """ def test_bitwise_operators(): - """Bitwise operators""" + """位运算符""" - # AND - # Sets each bit to 1 if both bits are 1. + # 与运算 + # 同位都为1,则取1,否则为0. # # Example: # 5 = 0b0101 # 3 = 0b0011 assert 5 & 3 == 1 # 0b0001 - # OR - # Sets each bit to 1 if one of two bits is 1. + # 或运算 + # 如果两个位中有一个为1,则设置每个位为1。 # # Example: # 5 = 0b0101 # 3 = 0b0011 assert 5 | 3 == 7 # 0b0111 - # NOT - # Inverts all the bits. + # 非运算 + # 反转所有位。 assert ~5 == -6 - # XOR - # Sets each bit to 1 if only one of two bits is 1. + # 异或运算 + # 当两个位中只有一个为1时,将每个位设为1。 # - # Example: + # Example:· # 5 = 0b0101 # 3 = 0b0011 number = 5 # 0b0101 number ^= 3 # 0b0011 assert 5 ^ 3 == 6 # 0b0110 - # Signed right shift - # Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost - # bits fall off. + # 右移运算 + # 通过将最左边位的副本从左边推入,向右移动,并让最右边位位脱落。 # # Example: # 5 = 0b0101 assert 5 >> 1 == 2 # 0b0010 assert 5 >> 2 == 1 # 0b0001 - # Zero fill left shift - # Shift left by pushing zeros in from the right and let the leftmost bits fall off. + # 左移0填充 + # 从右往左推0,让最左边的位去掉。 # # Example: # 5 = 0b0101 diff --git a/src/operators/test_comparison.py b/src/operators/test_comparison.py index 55ce1492..0f336c16 100644 --- a/src/operators/test_comparison.py +++ b/src/operators/test_comparison.py @@ -1,36 +1,36 @@ -"""Comparison operators +""" 比较运算符 @see: https://www.w3schools.com/python/python_operators.asp -Comparison operators are used to compare two values. +比较运算符用于比较两个值。 """ def test_comparison_operators(): """Comparison operators""" - # Equal. + # 等于. number = 5 assert number == 5 - # Not equal. + # 不等于. number = 5 assert number != 3 - # Greater than. + # 大于. number = 5 assert number > 3 - # Less than. + # 小于. number = 5 assert number < 8 - # Greater than or equal to + # 大于或等于 number = 5 assert number >= 5 assert number >= 4 - # Less than or equal to + # 小于或等于 number = 5 assert number <= 5 assert number <= 6 diff --git a/src/operators/test_identity.py b/src/operators/test_identity.py index 1450801c..628f33a0 100644 --- a/src/operators/test_identity.py +++ b/src/operators/test_identity.py @@ -1,35 +1,33 @@ -"""Identity operators +"""恒等运算符 @see: https://www.w3schools.com/python/python_operators.asp -Identity operators are used to compare the objects, not if they are equal, but if they are actually -the same object, with the same memory location. +恒等运算符用于比较对象,不是比较它们是否相等,而是比较它们是否相等 +相同的对象,相同的内存位置。 """ def test_identity_operators(): - """Identity operators""" + """恒等运算符""" - # Let's illustrate identity operators based on the following lists. + # 让我们根据下面的列表演示恒等运算符。 first_fruits_list = ["apple", "banana"] second_fruits_list = ["apple", "banana"] third_fruits_list = first_fruits_list # is - # Returns true if both variables are the same object. + # 如果两个变量是同一个对象,则返回true. # Example: - # first_fruits_list and third_fruits_list are the same objects. + # First_fruits_list和third_fruits_list是相同的对象。 assert first_fruits_list is third_fruits_list # is not - # Returns true if both variables are not the same object. + # 如果两个变量不是同一个对象,则返回true。 # Example: - # first_fruits_list and second_fruits_list are not the same objects, even if they have - # the same content + # First_fruits_list和second_fruits_list不是相同的对象,即使它们有相同的内容 assert first_fruits_list is not second_fruits_list - # To demonstrate the difference between "is" and "==": this comparison returns True because - # first_fruits_list is equal to second_fruits_list. + # 为了演示"is"和"=="之间的区别:这个比较返回True因为First_fruits_list等于second_fruits_list。 assert first_fruits_list == second_fruits_list diff --git a/src/operators/test_logical.py b/src/operators/test_logical.py index 87aa7592..7d088577 100644 --- a/src/operators/test_logical.py +++ b/src/operators/test_logical.py @@ -1,28 +1,28 @@ -"""Logical operators +"""逻辑运算符 @see: https://www.w3schools.com/python/python_operators.asp -Logical operators are used to combine conditional statements. +逻辑运算符用于组合条件语句。 """ def test_logical_operators(): - """Logical operators""" + """逻辑运算符""" - # Let's work with these number to illustrate logic operators. + # 让我们使用这些数字来说明逻辑运算符。 first_number = 5 second_number = 10 # and - # Returns True if both statements are true. + # 如果两个语句都为真,则返回True。 assert first_number > 0 and second_number < 20 # or - # Returns True if one of the statements is true + # 如果其中一个语句为真,则返回True assert first_number > 5 or second_number < 20 # not - # Reverse the result, returns False if the result is true. + # 反转结果,如果结果为真则返回False。 # pylint: disable=unneeded-not assert not first_number == second_number assert first_number != second_number diff --git a/src/operators/test_membership.py b/src/operators/test_membership.py index cf5ed03e..dc5e6385 100644 --- a/src/operators/test_membership.py +++ b/src/operators/test_membership.py @@ -1,25 +1,25 @@ -"""Membership operators +"""成员运算符 @see: https://www.w3schools.com/python/python_operators.asp -Membership operators are used to test if a sequence is presented in an object. +成员运算符用于测试一个序列是否出现在一个对象中。 """ def test_membership_operators(): - """Membership operators""" + """成员运算符""" - # Let's use the following fruit list to illustrate membership concept. + # 让我们使用下面的水果列表来说明成员概念。 fruit_list = ["apple", "banana"] # in - # Returns True if a sequence with the specified value is present in the object. + # 如果对象中存在具有指定值的序列,则返回True。 - # Returns True because a sequence with the value "banana" is in the list + # 返回True,因为列表中有一个值为“banana”的序列 assert "banana" in fruit_list # not in - # Returns True if a sequence with the specified value is not present in the object + # 如果对象中不存在具有指定值的序列,则返回True - # Returns True because a sequence with the value "pineapple" is not in the list. + # 返回True,因为值为"pineapple"的序列不在列表中。 assert "pineapple" not in fruit_list From e8c3adc5b6e4cfba5f879b434a17c8e9e7029ea1 Mon Sep 17 00:00:00 2001 From: dongjingxiang <534458392@qq.com> Date: Mon, 28 Jun 2021 20:08:45 +0800 Subject: [PATCH 2/8] =?UTF-8?q?=E7=BF=BB=E8=AF=91=E5=AD=A6=E4=B9=A0Python?= =?UTF-8?q?=20=E4=B8=AD=E6=96=87=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.en.md | 220 ++++++++++++++++++++++++++++++++++++++++ README.md | 259 ++++++++++++++++++++++-------------------------- README.pt-BR.md | 2 +- README.zh-CN.md | 203 ------------------------------------- 4 files changed, 342 insertions(+), 342 deletions(-) create mode 100644 README.en.md delete mode 100644 README.zh-CN.md diff --git a/README.en.md b/README.en.md new file mode 100644 index 00000000..2a39aa0b --- /dev/null +++ b/README.en.md @@ -0,0 +1,220 @@ +# Playground and Cheatsheet for Learning Python + +[](https://travis-ci.org/trekhleb/learn-python) + +> This is a collection of Python scripts that are split by [topics](#table-of-contents) and contain +code examples with explanations, different use cases and links to further readings. + +_Read this in_ [_Português_](README.pt-BR.md). + +It is a **playground** because you may change or add the code to see how it works +and [test it out](#testing-the-code) using assertions. It also allows you +to [lint the code](#linting-the-code) you've wrote and check if it fits to Python code style guide. +Altogether it might make your learning process to be more interactive and it might help you to keep +code quality pretty high from very beginning. + +It is a **cheatsheet** because you may get back to these code examples once you want to recap the +syntax of [standard Python statements and constructions](#table-of-contents). Also because the +code is full of assertions you'll be able to see expected functions/statements output right away +without launching them. + +> _You might also be interested in 🤖 [Interactive Machine Learning Experiments](https://github.com/trekhleb/machine-learning-experiments)_ + +## How to Use This Repository + +Each Python script in this repository has the following structure: + +```python +"""Lists <--- Name of the topic here + +# @see: https://www.learnpython.org/en/Lists <-- Link to further readings goes here + +Here might go more detailed explanation of the current topic (i.e. general info about Lists). +""" + + +def test_list_type(): + """Explanation of sub-topic goes here. + + Each file contains test functions that illustrate sub-topics (i.e. lists type, lists methods). + """ + + # Here is an example of how to build a list. <-- Comments here explain the action + squares = [1, 4, 9, 16, 25] + + # Lists can be indexed and sliced. + # Indexing returns the item. + assert squares[0] == 1 # <-- Assertions here illustrate the result. + # Slicing returns a new list. + assert squares[-3:] == [9, 16, 25] # <-- Assertions here illustrate the result. +``` + +So normally you might want to do the following: + +- [Find the topic](#table-of-contents) you want to learn or recap. +- Read comments and/or documentation that is linked in each script's docstring (as in example above). +- Look at code examples and assertions to see usage examples and expected output. +- Change code or add new assertions to see how things work. +- [Run tests](#testing-the-code) and [lint the code](#linting-the-code) to see if it work and is +written correctly. + +## Table of Contents + +1. **Getting Started** + - [What is Python](src/getting_started/what_is_python.md) + - [Python Syntax](src/getting_started/python_syntax.md) + - [Variables](src/getting_started/test_variables.py) +2. **Operators** + - [Arithmetic Operators](src/operators/test_arithmetic.py) (`+`, `-`, `*`, `/`, `//`, `%`, `**`) + - [Bitwise Operators](src/operators/test_bitwise.py) (`&`, `|`, `^`, `>>`, `<<`, `~`) + - [Assignment Operators](src/operators/test_assigment.py) (`=`, `+=`, `-=`, `/=`, `//=` etc.) + - [Comparison Operator](src/operators/test_comparison.py) (`==`, `!=`, `>`, `<`, `>=`, `<=`) + - [Logical Operators](src/operators/test_logical.py) (`and`, `or`, `not`) + - [Identity Operators](src/operators/test_identity.py) (`is`, `is not`) + - [Membership Operators](src/operators/test_membership.py) (`in`, `not in`) +3. **Data Types** + - [Numbers](src/data_types/test_numbers.py) (including booleans) + - [Strings](src/data_types/test_strings.py) and their methods + - [Lists](src/data_types/test_lists.py) and their methods (including list comprehensions) + - [Tuples](src/data_types/test_tuples.py) + - [Sets](src/data_types/test_sets.py) and their methods + - [Dictionaries](src/data_types/test_dictionaries.py) + - [Type Casting](src/data_types/test_type_casting.py) +4. **Control Flow** + - [The `if` statement](src/control_flow/test_if.py) + - [The `for` statement](src/control_flow/test_for.py) (and `range()` function) + - [The `while` statement](src/control_flow/test_while.py) + - [The `try` statements](src/control_flow/test_try.py) + - [The `break` statement](src/control_flow/test_break.py) + - [The `continue` statement](src/control_flow/test_continue.py) +5. **Functions** + - [Function Definition](src/functions/test_function_definition.py) (`def` and `return` statements) + - [Scopes of Variables Inside Functions](src/functions/test_function_scopes.py) (`global` and `nonlocal` statements) + - [Default Argument Values](src/functions/test_function_default_arguments.py) + - [Keyword Arguments](src/functions/test_function_keyword_arguments.py) + - [Arbitrary Argument Lists](src/functions/test_function_arbitrary_arguments.py) + - [Unpacking Argument Lists](src/functions/test_function_unpacking_arguments.py) (`*` and `**` statements) + - [Lambda Expressions](src/functions/test_lambda_expressions.py) (`lambda` statement) + - [Documentation Strings](src/functions/test_function_documentation_string.py) + - [Function Annotations](src/functions/test_function_annotations.py) + - [Function Decorators](src/functions/test_function_decorators.py) +6. **Classes** + - [Class Definition](src/classes/test_class_definition.py) (`class` statement) + - [Class Objects](src/classes/test_class_objects.py) + - [Instance Objects](src/classes/test_instance_objects.py) + - [Method Objects](src/classes/test_method_objects.py) + - [Class and Instance Variables](src/classes/test_class_and_instance_variables.py) + - [Inheritance](src/classes/test_inheritance.py) + - [Multiple Inheritance](src/classes/test_multiple_inheritance.py) +7. **Modules** + - [Modules](src/modules/test_modules.py) (`import` statement) + - [Packages](src/modules/test_packages.py) +8. **Errors and Exceptions** + - [Handling Exceptions](src/exceptions/test_handle_exceptions.py) (`try` statement) + - [Raising Exceptions](src/exceptions/test_raise_exceptions.py) (`raise` statement) +9. **Files** + - [Reading and Writing](src/files/test_file_reading.py) (`with` statement) + - [Methods of File Objects](src/files/test_file_methods.py) +10. **Additions** + - [The `pass` statement](src/additions/test_pass.py) + - [Generators](src/additions/test_generators.py) (`yield` statement) +11. **Brief Tour of the Standard Libraries** + - [Serialization](src/standard_libraries/test_json.py) (`json` library) + - [File Wildcards](src/standard_libraries/test_glob.py) (`glob` library) + - [String Pattern Matching](src/standard_libraries/test_re.py) (`re` library) + - [Mathematics](src/standard_libraries/test_math.py) (`math`, `random`, `statistics` libraries) + - [Dates and Times](src/standard_libraries/test_datetime.py) (`datetime` library) + - [Data Compression](src/standard_libraries/test_zlib.py) (`zlib` library) + +## Prerequisites + +**Installing Python** + +Make sure that you have [Python3 installed](https://realpython.com/installing-python/) on your machine. + +You might want to use [venv](https://docs.python.org/3/library/venv.html) standard Python library +to create virtual environments and have Python, pip and all dependent packages to be installed and +served from the local project directory to avoid messing with system wide packages and their +versions. + +Depending on your installation you might have access to Python3 interpreter either by +running `python` or `python3`. The same goes for pip package manager - it may be accessible either +by running `pip` or `pip3`. + +You may check your Python version by running: + +```bash +python --version +``` + +Note that in this repository whenever you see `python` it will be assumed that it is Python **3**. + +**Installing dependencies** + +Install all dependencies that are required for the project by running: + +```bash +pip install -r requirements.txt +``` + +## Testing the Code + +Tests are made using [pytest](https://docs.pytest.org/en/latest/) framework. + +You may add new tests for yourself by adding files and functions with `test_` prefix +(i.e. `test_topic.py` with `def test_sub_topic()` function inside). + +To run all the tests please execute the following command from the project root folder: + +```bash +pytest +``` + +To run specific tests please execute: + +```bash +pytest ./path/to/the/test_file.py +``` + +## Linting the Code + +Linting is done using [pylint](http://pylint.pycqa.org/) and [flake8](http://flake8.pycqa.org/en/latest/) libraries. + +### PyLint + +To check if the code is written with respect +to [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide please run: + +```bash +pylint ./src/ +``` + +In case if linter will detect error (i.e. `missing-docstring`) you may want to read more about +specific error by running: + +```bash +pylint --help-msg=missing-docstring +``` + +[More about PyLint](http://pylint.pycqa.org/) + +### Flake8 + +To check if the code is written with respect +to [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide please run: + +```bash +flake8 ./src +``` + +Or if you want to have more detailed output you may run: + +```bash +flake8 ./src --statistics --show-source --count +``` + +[More about Flake8](http://flake8.pycqa.org/en/latest/) + +## Supporting the project + +You may support this project via ❤️️ [GitHub](https://github.com/sponsors/trekhleb) or ❤️️ [Patreon](https://www.patreon.com/trekhleb). diff --git a/README.md b/README.md index 2a39aa0b..672e0868 100644 --- a/README.md +++ b/README.md @@ -1,145 +1,136 @@ -# Playground and Cheatsheet for Learning Python +# 学习 Python 的游乐场(playground)和备忘单(cheatsheet) [](https://travis-ci.org/trekhleb/learn-python) -> This is a collection of Python scripts that are split by [topics](#table-of-contents) and contain -code examples with explanations, different use cases and links to further readings. +> 这是 Python 脚本的集合,按 [主题](目录)划分,包含带有解释的代码示例、不同的用例和进一步阅读的链接。 _Read this in_ [_Português_](README.pt-BR.md). -It is a **playground** because you may change or add the code to see how it works -and [test it out](#testing-the-code) using assertions. It also allows you -to [lint the code](#linting-the-code) you've wrote and check if it fits to Python code style guide. -Altogether it might make your learning process to be more interactive and it might help you to keep -code quality pretty high from very beginning. +这是一个**游乐场(playground)**,因为您可以更改或添加代码以查看它是如何工作的, +并使用断言 [测试代码](#testing-the-code)。它还允许您 [lint the code](#linting-the-code) +并检查它是否符合 Python 代码风格指南。 +总而言之,它可能会使您的学习过程更具交互性,并且可能会帮助您从一开始就保持较高的代码质量。 -It is a **cheatsheet** because you may get back to these code examples once you want to recap the -syntax of [standard Python statements and constructions](#table-of-contents). Also because the -code is full of assertions you'll be able to see expected functions/statements output right away -without launching them. +这是一个**备忘单(cheatsheet)**,因为一旦您想回顾[标准 Python 语句和结构](#table-of-contents)的语法,您可能会回到这些代码示例。 +此外,由于代码中充满了断言,您无需启动它们就可以立即看到预期的函数语句输出。 -> _You might also be interested in 🤖 [Interactive Machine Learning Experiments](https://github.com/trekhleb/machine-learning-experiments)_ +> _你可能也对🤖感兴趣 [交互式机器学习实验](https://github.com/trekhleb/machine-learning-experiments)_ -## How to Use This Repository +## 如何使用此存储库 -Each Python script in this repository has the following structure: +此存储库中的每个 Python 脚本都具有以下结构: ```python -"""Lists <--- Name of the topic here +"""Lists <--- 这里的主题名称 -# @see: https://www.learnpython.org/en/Lists <-- Link to further readings goes here +# @see: https://www.learnpython.org/en/Lists <-- 进一步阅读的链接在这里 -Here might go more detailed explanation of the current topic (i.e. general info about Lists). +这里可能会对当前主题进行更详细的解释(即关于列表的一般信息)。 """ def test_list_type(): - """Explanation of sub-topic goes here. - - Each file contains test functions that illustrate sub-topics (i.e. lists type, lists methods). + """ + 子主题的解释在这里。每个文件都包含说明子主题的测试函数(即列表类型、列表方法)。 """ - # Here is an example of how to build a list. <-- Comments here explain the action + # 以下是如何构建列表的示例。 <-- 这里的评论解释了这个动作 squares = [1, 4, 9, 16, 25] - # Lists can be indexed and sliced. - # Indexing returns the item. - assert squares[0] == 1 # <-- Assertions here illustrate the result. - # Slicing returns a new list. - assert squares[-3:] == [9, 16, 25] # <-- Assertions here illustrate the result. + # 列表可以被索引和切片。 + # 索引返回项目。 + assert squares[0] == 1 # <-- 这里的断言说明了结果。 + # 切片返回一个新列表。 + assert squares[-3:] == [9, 16, 25] # <-- 这里的断言说明了结果。 ``` -So normally you might want to do the following: - -- [Find the topic](#table-of-contents) you want to learn or recap. -- Read comments and/or documentation that is linked in each script's docstring (as in example above). -- Look at code examples and assertions to see usage examples and expected output. -- Change code or add new assertions to see how things work. -- [Run tests](#testing-the-code) and [lint the code](#linting-the-code) to see if it work and is -written correctly. - -## Table of Contents - -1. **Getting Started** - - [What is Python](src/getting_started/what_is_python.md) - - [Python Syntax](src/getting_started/python_syntax.md) - - [Variables](src/getting_started/test_variables.py) -2. **Operators** - - [Arithmetic Operators](src/operators/test_arithmetic.py) (`+`, `-`, `*`, `/`, `//`, `%`, `**`) - - [Bitwise Operators](src/operators/test_bitwise.py) (`&`, `|`, `^`, `>>`, `<<`, `~`) - - [Assignment Operators](src/operators/test_assigment.py) (`=`, `+=`, `-=`, `/=`, `//=` etc.) - - [Comparison Operator](src/operators/test_comparison.py) (`==`, `!=`, `>`, `<`, `>=`, `<=`) - - [Logical Operators](src/operators/test_logical.py) (`and`, `or`, `not`) - - [Identity Operators](src/operators/test_identity.py) (`is`, `is not`) - - [Membership Operators](src/operators/test_membership.py) (`in`, `not in`) -3. **Data Types** - - [Numbers](src/data_types/test_numbers.py) (including booleans) - - [Strings](src/data_types/test_strings.py) and their methods - - [Lists](src/data_types/test_lists.py) and their methods (including list comprehensions) - - [Tuples](src/data_types/test_tuples.py) - - [Sets](src/data_types/test_sets.py) and their methods - - [Dictionaries](src/data_types/test_dictionaries.py) +所以通常你可能想要执行以下操作: + +- [Find the topic](#table-of-contents)你想学习或回顾。 +- 阅读每个脚本的文档字符串中链接的注释和/或文档(如上例所示)。 +- 查看代码示例和断言以查看使用示例和预期输出。 +- 更改代码或添加新断言以查看工作方式。 +- [Run tests](#testing-the-code) and [lint the code](#linting-the-code) 看看它是否有效并且是否正确写入。 + +## 目录 + +1. **入门** + - [什么是 Python](src/getting_started/what_is_python.md) + - [Python 语法](src/getting_started/python_syntax.md) + - [变量](src/getting_started/test_variables.py) +2. **运算符** + - [算术运算符](src/operators/test_arithmetic.py) (`+`, `-`, `*`, `/`, `//`, `%`, `**`) + - [位运算符](src/operators/test_bitwise.py) (`&`, `|`, `^`, `>>`, `<<`, `~`) + - [赋值运算符](src/operators/test_assigment.py) (`=`, `+=`, `-=`, `/=`, `//=` etc.) + - [比较运算符](src/operators/test_comparison.py) (`==`, `!=`, `>`, `<`, `>=`, `<=`) + - [逻辑运算符](src/operators/test_logical.py) (`and`, `or`, `not`) + - [恒等运算符](src/operators/test_identity.py) (`is`, `is not`) + - [成员运算符](src/operators/test_membership.py) (`in`, `not in`) +3. **数据类型** + - [数字](src/data_types/test_numbers.py) (其中包括布尔值) + - [字符串](src/data_types/test_strings.py) 以及方法 + - [列表](src/data_types/test_lists.py) 以及方法(包括列表推导式) + - [元组](src/data_types/test_tuples.py) + - [集合](src/data_types/test_sets.py)及其方法 + - [字典](src/data_types/test_dictionaries.py) - [Type Casting](src/data_types/test_type_casting.py) -4. **Control Flow** - - [The `if` statement](src/control_flow/test_if.py) - - [The `for` statement](src/control_flow/test_for.py) (and `range()` function) - - [The `while` statement](src/control_flow/test_while.py) - - [The `try` statements](src/control_flow/test_try.py) - - [The `break` statement](src/control_flow/test_break.py) - - [The `continue` statement](src/control_flow/test_continue.py) -5. **Functions** - - [Function Definition](src/functions/test_function_definition.py) (`def` and `return` statements) - - [Scopes of Variables Inside Functions](src/functions/test_function_scopes.py) (`global` and `nonlocal` statements) - - [Default Argument Values](src/functions/test_function_default_arguments.py) - - [Keyword Arguments](src/functions/test_function_keyword_arguments.py) - - [Arbitrary Argument Lists](src/functions/test_function_arbitrary_arguments.py) - - [Unpacking Argument Lists](src/functions/test_function_unpacking_arguments.py) (`*` and `**` statements) - - [Lambda Expressions](src/functions/test_lambda_expressions.py) (`lambda` statement) - - [Documentation Strings](src/functions/test_function_documentation_string.py) - - [Function Annotations](src/functions/test_function_annotations.py) - - [Function Decorators](src/functions/test_function_decorators.py) -6. **Classes** - - [Class Definition](src/classes/test_class_definition.py) (`class` statement) - - [Class Objects](src/classes/test_class_objects.py) - - [Instance Objects](src/classes/test_instance_objects.py) - - [Method Objects](src/classes/test_method_objects.py) - - [Class and Instance Variables](src/classes/test_class_and_instance_variables.py) - - [Inheritance](src/classes/test_inheritance.py) - - [Multiple Inheritance](src/classes/test_multiple_inheritance.py) -7. **Modules** - - [Modules](src/modules/test_modules.py) (`import` statement) - - [Packages](src/modules/test_packages.py) -8. **Errors and Exceptions** - - [Handling Exceptions](src/exceptions/test_handle_exceptions.py) (`try` statement) - - [Raising Exceptions](src/exceptions/test_raise_exceptions.py) (`raise` statement) -9. **Files** - - [Reading and Writing](src/files/test_file_reading.py) (`with` statement) - - [Methods of File Objects](src/files/test_file_methods.py) -10. **Additions** - - [The `pass` statement](src/additions/test_pass.py) - - [Generators](src/additions/test_generators.py) (`yield` statement) -11. **Brief Tour of the Standard Libraries** - - [Serialization](src/standard_libraries/test_json.py) (`json` library) - - [File Wildcards](src/standard_libraries/test_glob.py) (`glob` library) - - [String Pattern Matching](src/standard_libraries/test_re.py) (`re` library) - - [Mathematics](src/standard_libraries/test_math.py) (`math`, `random`, `statistics` libraries) - - [Dates and Times](src/standard_libraries/test_datetime.py) (`datetime` library) - - [Data Compression](src/standard_libraries/test_zlib.py) (`zlib` library) - -## Prerequisites - -**Installing Python** - -Make sure that you have [Python3 installed](https://realpython.com/installing-python/) on your machine. - -You might want to use [venv](https://docs.python.org/3/library/venv.html) standard Python library -to create virtual environments and have Python, pip and all dependent packages to be installed and -served from the local project directory to avoid messing with system wide packages and their -versions. - -Depending on your installation you might have access to Python3 interpreter either by -running `python` or `python3`. The same goes for pip package manager - it may be accessible either -by running `pip` or `pip3`. +4. **控制** + - [if](src/control_flow/test_if.py) + - [for](src/control_flow/test_for.py) (以及 `range()` 函数) + - [while](src/control_flow/test_while.py) + - [try](src/control_flow/test_try.py) + - [break](src/control_flow/test_break.py) + - [continue](src/control_flow/test_continue.py) +5. **函数** + - [函数定义](src/functions/test_function_definition.py) (`def` and `return` statements) + - [函数内部变量的作用域](src/functions/test_function_scopes.py) (`global` and `nonlocal` statements) + - [默认参数值](src/functions/test_function_default_arguments.py) + - [关键字参数](src/functions/test_function_keyword_arguments.py) + - [任意的参数列表](src/functions/test_function_arbitrary_arguments.py) + - [拆包参数列表](src/functions/test_function_unpacking_arguments.py) (`*` and `**` statements) + - [Lambda表达式](src/functions/test_lambda_expressions.py) (`lambda` statement) + - [文档字符串](src/functions/test_function_documentation_string.py) + - [函数注释](src/functions/test_function_annotations.py) + - [函数修饰符](src/functions/test_function_decorators.py) +6. **类** + - [类定义](src/classes/test_class_definition.py) (`class` statement) + - [类对象](src/classes/test_class_objects.py) + - [实例对象](src/classes/test_instance_objects.py) + - [方法对象](src/classes/test_method_objects.py) + - [类和实例变量](src/classes/test_class_and_instance_variables.py) + - [继承](src/classes/test_inheritance.py) + - [多重继承](src/classes/test_multiple_inheritance.py) +7. **组件** + - [组件](src/modules/test_modules.py) (`import` statement) + - [包](src/modules/test_packages.py) +8. **错误和异常** + - [处理异常](src/exceptions/test_handle_exceptions.py) (`try` statement) + - [提高异常](src/exceptions/test_raise_exceptions.py) (`raise` statement) +9. **文件** + - [读与写](src/files/test_file_reading.py) (`with` statement) + - [文件对象的方法](src/files/test_file_methods.py) +10. **附加物** + - [`pass` 声明](src/additions/test_pass.py) + - [生成器](src/additions/test_generators.py) (`yield` 声明) +11. **标准库简介** + - [序列化](src/standard_libraries/test_json.py) (`json` library) + - [文件通配符](src/standard_libraries/test_glob.py) (`glob` library) + - [字符串匹配](src/standard_libraries/test_re.py) (`re` library) + - [数学运算](src/standard_libraries/test_math.py) (`math`, `random`, `statistics` libraries) + - [日期和时间](src/standard_libraries/test_datetime.py) (`datetime` library) + - [数据压缩](src/standard_libraries/test_zlib.py) (`zlib` library) + +## 预备知识 + +**安装Python** + +确保你安装了[Python3](https://realpython.com/installing-python/) on your machine. + +你可能想要使用[venv](https://docs.python.org/3/library/venv.html)标准Python库 +创建虚拟环境并安装Python、pip和所有依赖包从本地项目目录提供,以避免与系统范围的包及其版本。 + +根据你的安装,你可以通过运行`python` 或 `python3`。pip包管理器也是如此——它也可能是可访问的 +通过运行 `pip `或` pip3 `。 You may check your Python version by running: @@ -157,40 +148,39 @@ Install all dependencies that are required for the project by running: pip install -r requirements.txt ``` -## Testing the Code +## 测试代码 -Tests are made using [pytest](https://docs.pytest.org/en/latest/) framework. +测试使用 [pytest](https://docs.pytest.org/en/latest/) 框架. -You may add new tests for yourself by adding files and functions with `test_` prefix -(i.e. `test_topic.py` with `def test_sub_topic()` function inside). +您可以通过 `test_` 作为前缀添加文件和函数为自己添加新的测试 +(例如: 在 `test_topic.py` 里添加 `def test_sub_topic()` 函数). -To run all the tests please execute the following command from the project root folder: +要运行所有测试,请从项目根文件夹执行以下命令: ```bash pytest ``` -To run specific tests please execute: +要运行特定的测试,请执行: ```bash pytest ./path/to/the/test_file.py ``` -## Linting the Code +## 代码检测 -Linting is done using [pylint](http://pylint.pycqa.org/) and [flake8](http://flake8.pycqa.org/en/latest/) libraries. +代码检测用的是 [pylint](http://pylint.pycqa.org/) 和 [flake8](http://flake8.pycqa.org/en/latest/) 库. ### PyLint -To check if the code is written with respect -to [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide please run: +来检查代码是否按 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 规定编写,请执行: ```bash pylint ./src/ ``` -In case if linter will detect error (i.e. `missing-docstring`) you may want to read more about -specific error by running: +以防linter检测到错误 (i.e. `missing-docstring`) 你可能想读更多关于 +具体运行错误: ```bash pylint --help-msg=missing-docstring @@ -200,21 +190,14 @@ pylint --help-msg=missing-docstring ### Flake8 -To check if the code is written with respect -to [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide please run: +来检查代码是否按 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 规定编写,请执行: ```bash flake8 ./src ``` -Or if you want to have more detailed output you may run: +或者,如果你想有更详细的输出,你可以运行: ```bash flake8 ./src --statistics --show-source --count ``` - -[More about Flake8](http://flake8.pycqa.org/en/latest/) - -## Supporting the project - -You may support this project via ❤️️ [GitHub](https://github.com/sponsors/trekhleb) or ❤️️ [Patreon](https://www.patreon.com/trekhleb). diff --git a/README.pt-BR.md b/README.pt-BR.md index e6bd025f..9008a1ff 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -5,7 +5,7 @@ > Essa é uma coleção de scripts Python dividida em [tópicos](#índice) que contém exemplos de código com explicações, diferentes usos e links para outras leituras. -_Ler em_ [_English_](README.md). +_Ler em_ [_English_](README.en.md). É um **playground** porque você pode fazer alterações no código para ver como ele se comporta, além de [testá-lo](#testando-o-código) usando asserções. Também é possível diff --git a/README.zh-CN.md b/README.zh-CN.md deleted file mode 100644 index 672e0868..00000000 --- a/README.zh-CN.md +++ /dev/null @@ -1,203 +0,0 @@ -# 学习 Python 的游乐场(playground)和备忘单(cheatsheet) - -[](https://travis-ci.org/trekhleb/learn-python) - -> 这是 Python 脚本的集合,按 [主题](目录)划分,包含带有解释的代码示例、不同的用例和进一步阅读的链接。 - -_Read this in_ [_Português_](README.pt-BR.md). - -这是一个**游乐场(playground)**,因为您可以更改或添加代码以查看它是如何工作的, -并使用断言 [测试代码](#testing-the-code)。它还允许您 [lint the code](#linting-the-code) -并检查它是否符合 Python 代码风格指南。 -总而言之,它可能会使您的学习过程更具交互性,并且可能会帮助您从一开始就保持较高的代码质量。 - -这是一个**备忘单(cheatsheet)**,因为一旦您想回顾[标准 Python 语句和结构](#table-of-contents)的语法,您可能会回到这些代码示例。 -此外,由于代码中充满了断言,您无需启动它们就可以立即看到预期的函数语句输出。 - -> _你可能也对🤖感兴趣 [交互式机器学习实验](https://github.com/trekhleb/machine-learning-experiments)_ - -## 如何使用此存储库 - -此存储库中的每个 Python 脚本都具有以下结构: - -```python -"""Lists <--- 这里的主题名称 - -# @see: https://www.learnpython.org/en/Lists <-- 进一步阅读的链接在这里 - -这里可能会对当前主题进行更详细的解释(即关于列表的一般信息)。 -""" - - -def test_list_type(): - """ - 子主题的解释在这里。每个文件都包含说明子主题的测试函数(即列表类型、列表方法)。 - """ - - # 以下是如何构建列表的示例。 <-- 这里的评论解释了这个动作 - squares = [1, 4, 9, 16, 25] - - # 列表可以被索引和切片。 - # 索引返回项目。 - assert squares[0] == 1 # <-- 这里的断言说明了结果。 - # 切片返回一个新列表。 - assert squares[-3:] == [9, 16, 25] # <-- 这里的断言说明了结果。 -``` - -所以通常你可能想要执行以下操作: - -- [Find the topic](#table-of-contents)你想学习或回顾。 -- 阅读每个脚本的文档字符串中链接的注释和/或文档(如上例所示)。 -- 查看代码示例和断言以查看使用示例和预期输出。 -- 更改代码或添加新断言以查看工作方式。 -- [Run tests](#testing-the-code) and [lint the code](#linting-the-code) 看看它是否有效并且是否正确写入。 - -## 目录 - -1. **入门** - - [什么是 Python](src/getting_started/what_is_python.md) - - [Python 语法](src/getting_started/python_syntax.md) - - [变量](src/getting_started/test_variables.py) -2. **运算符** - - [算术运算符](src/operators/test_arithmetic.py) (`+`, `-`, `*`, `/`, `//`, `%`, `**`) - - [位运算符](src/operators/test_bitwise.py) (`&`, `|`, `^`, `>>`, `<<`, `~`) - - [赋值运算符](src/operators/test_assigment.py) (`=`, `+=`, `-=`, `/=`, `//=` etc.) - - [比较运算符](src/operators/test_comparison.py) (`==`, `!=`, `>`, `<`, `>=`, `<=`) - - [逻辑运算符](src/operators/test_logical.py) (`and`, `or`, `not`) - - [恒等运算符](src/operators/test_identity.py) (`is`, `is not`) - - [成员运算符](src/operators/test_membership.py) (`in`, `not in`) -3. **数据类型** - - [数字](src/data_types/test_numbers.py) (其中包括布尔值) - - [字符串](src/data_types/test_strings.py) 以及方法 - - [列表](src/data_types/test_lists.py) 以及方法(包括列表推导式) - - [元组](src/data_types/test_tuples.py) - - [集合](src/data_types/test_sets.py)及其方法 - - [字典](src/data_types/test_dictionaries.py) - - [Type Casting](src/data_types/test_type_casting.py) -4. **控制** - - [if](src/control_flow/test_if.py) - - [for](src/control_flow/test_for.py) (以及 `range()` 函数) - - [while](src/control_flow/test_while.py) - - [try](src/control_flow/test_try.py) - - [break](src/control_flow/test_break.py) - - [continue](src/control_flow/test_continue.py) -5. **函数** - - [函数定义](src/functions/test_function_definition.py) (`def` and `return` statements) - - [函数内部变量的作用域](src/functions/test_function_scopes.py) (`global` and `nonlocal` statements) - - [默认参数值](src/functions/test_function_default_arguments.py) - - [关键字参数](src/functions/test_function_keyword_arguments.py) - - [任意的参数列表](src/functions/test_function_arbitrary_arguments.py) - - [拆包参数列表](src/functions/test_function_unpacking_arguments.py) (`*` and `**` statements) - - [Lambda表达式](src/functions/test_lambda_expressions.py) (`lambda` statement) - - [文档字符串](src/functions/test_function_documentation_string.py) - - [函数注释](src/functions/test_function_annotations.py) - - [函数修饰符](src/functions/test_function_decorators.py) -6. **类** - - [类定义](src/classes/test_class_definition.py) (`class` statement) - - [类对象](src/classes/test_class_objects.py) - - [实例对象](src/classes/test_instance_objects.py) - - [方法对象](src/classes/test_method_objects.py) - - [类和实例变量](src/classes/test_class_and_instance_variables.py) - - [继承](src/classes/test_inheritance.py) - - [多重继承](src/classes/test_multiple_inheritance.py) -7. **组件** - - [组件](src/modules/test_modules.py) (`import` statement) - - [包](src/modules/test_packages.py) -8. **错误和异常** - - [处理异常](src/exceptions/test_handle_exceptions.py) (`try` statement) - - [提高异常](src/exceptions/test_raise_exceptions.py) (`raise` statement) -9. **文件** - - [读与写](src/files/test_file_reading.py) (`with` statement) - - [文件对象的方法](src/files/test_file_methods.py) -10. **附加物** - - [`pass` 声明](src/additions/test_pass.py) - - [生成器](src/additions/test_generators.py) (`yield` 声明) -11. **标准库简介** - - [序列化](src/standard_libraries/test_json.py) (`json` library) - - [文件通配符](src/standard_libraries/test_glob.py) (`glob` library) - - [字符串匹配](src/standard_libraries/test_re.py) (`re` library) - - [数学运算](src/standard_libraries/test_math.py) (`math`, `random`, `statistics` libraries) - - [日期和时间](src/standard_libraries/test_datetime.py) (`datetime` library) - - [数据压缩](src/standard_libraries/test_zlib.py) (`zlib` library) - -## 预备知识 - -**安装Python** - -确保你安装了[Python3](https://realpython.com/installing-python/) on your machine. - -你可能想要使用[venv](https://docs.python.org/3/library/venv.html)标准Python库 -创建虚拟环境并安装Python、pip和所有依赖包从本地项目目录提供,以避免与系统范围的包及其版本。 - -根据你的安装,你可以通过运行`python` 或 `python3`。pip包管理器也是如此——它也可能是可访问的 -通过运行 `pip `或` pip3 `。 - -You may check your Python version by running: - -```bash -python --version -``` - -Note that in this repository whenever you see `python` it will be assumed that it is Python **3**. - -**Installing dependencies** - -Install all dependencies that are required for the project by running: - -```bash -pip install -r requirements.txt -``` - -## 测试代码 - -测试使用 [pytest](https://docs.pytest.org/en/latest/) 框架. - -您可以通过 `test_` 作为前缀添加文件和函数为自己添加新的测试 -(例如: 在 `test_topic.py` 里添加 `def test_sub_topic()` 函数). - -要运行所有测试,请从项目根文件夹执行以下命令: - -```bash -pytest -``` - -要运行特定的测试,请执行: - -```bash -pytest ./path/to/the/test_file.py -``` - -## 代码检测 - -代码检测用的是 [pylint](http://pylint.pycqa.org/) 和 [flake8](http://flake8.pycqa.org/en/latest/) 库. - -### PyLint - -来检查代码是否按 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 规定编写,请执行: - -```bash -pylint ./src/ -``` - -以防linter检测到错误 (i.e. `missing-docstring`) 你可能想读更多关于 -具体运行错误: - -```bash -pylint --help-msg=missing-docstring -``` - -[More about PyLint](http://pylint.pycqa.org/) - -### Flake8 - -来检查代码是否按 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 规定编写,请执行: - -```bash -flake8 ./src -``` - -或者,如果你想有更详细的输出,你可以运行: - -```bash -flake8 ./src --statistics --show-source --count -``` From f548887a31431d8043a753981730f064176e18f0 Mon Sep 17 00:00:00 2001 From: "Mr.D" <534458392@qq.com> Date: Tue, 29 Jun 2021 09:23:19 +0800 Subject: [PATCH 3/8] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 672e0868..db741ece 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# 学习 Python 的游乐场(playground)和备忘单(cheatsheet) +# Python 学习笔记 [](https://travis-ci.org/trekhleb/learn-python) From 32468edf1cf0ccdcd9f2634d5b424a1d59a9f663 Mon Sep 17 00:00:00 2001 From: dongjingxiang <534458392@qq.com> Date: Tue, 29 Jun 2021 09:34:19 +0800 Subject: [PATCH 4/8] =?UTF-8?q?=E4=B8=AD=E6=96=87=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index db741ece..ad4ef08a 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,13 @@ > 这是 Python 脚本的集合,按 [主题](目录)划分,包含带有解释的代码示例、不同的用例和进一步阅读的链接。 -_Read this in_ [_Português_](README.pt-BR.md). -这是一个**游乐场(playground)**,因为您可以更改或添加代码以查看它是如何工作的, -并使用断言 [测试代码](#testing-the-code)。它还允许您 [lint the code](#linting-the-code) +这是一个**练习场**,因为您可以更改或添加代码以查看它是如何工作的, +并使用断言 [测试代码](#测试代码)。它还允许您 [代码检测](#代码检测) 并检查它是否符合 Python 代码风格指南。 总而言之,它可能会使您的学习过程更具交互性,并且可能会帮助您从一开始就保持较高的代码质量。 -这是一个**备忘单(cheatsheet)**,因为一旦您想回顾[标准 Python 语句和结构](#table-of-contents)的语法,您可能会回到这些代码示例。 +这是一个**备忘单**,因为一旦您想回顾[标准 Python 语句和结构](#目录)的语法,您可能会回到这些代码示例。 此外,由于代码中充满了断言,您无需启动它们就可以立即看到预期的函数语句输出。 > _你可能也对🤖感兴趣 [交互式机器学习实验](https://github.com/trekhleb/machine-learning-experiments)_ From 88d9916ab6b8788e42ca5db20ef4db24d5025dba Mon Sep 17 00:00:00 2001 From: dongjingxiang <534458392@qq.com> Date: Tue, 29 Jun 2021 09:38:43 +0800 Subject: [PATCH 5/8] =?UTF-8?q?=E4=B8=AD=E6=96=87=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ad4ef08a..b39325ca 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [](https://travis-ci.org/trekhleb/learn-python) -> 这是 Python 脚本的集合,按 [主题](目录)划分,包含带有解释的代码示例、不同的用例和进一步阅读的链接。 +> 这是 Python 脚本的集合,按 [目录](#目录)划分,包含带有解释的代码示例、不同的用例和进一步阅读的链接。 这是一个**练习场**,因为您可以更改或添加代码以查看它是如何工作的, From 0995a34c056d36ffec8027fad17f49958244638f Mon Sep 17 00:00:00 2001 From: dongjingxiang <534458392@qq.com> Date: Tue, 29 Jun 2021 20:09:39 +0800 Subject: [PATCH 6/8] =?UTF-8?q?=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- src/classes/test_class_definition.py | 35 ++-- src/classes/test_class_objects.py | 47 ++--- src/control_flow/test_break.py | 14 +- src/control_flow/test_continue.py | 16 +- src/control_flow/test_for.py | 51 ++--- src/control_flow/test_if.py | 9 +- src/control_flow/test_try.py | 26 ++- src/control_flow/test_while.py | 16 +- src/data_types/test_dictionaries.py | 51 +++-- src/data_types/test_lists.py | 185 ++++++++---------- src/data_types/test_sets.py | 37 ++-- src/data_types/test_strings.py | 134 ++++++------- src/data_types/test_tuples.py | 59 +++--- src/data_types/test_type_casting.py | 25 +-- src/functions/test_function_annotations.py | 16 +- .../test_function_arbitrary_arguments.py | 24 +-- src/functions/test_function_decorators.py | 69 ++++--- .../test_function_default_arguments.py | 16 +- src/functions/test_function_definition.py | 84 ++++---- .../test_function_documentation_string.py | 41 ++-- .../test_function_keyword_arguments.py | 53 +++-- src/functions/test_function_scopes.py | 90 ++++----- .../test_function_unpacking_arguments.py | 20 +- src/functions/test_lambda_expressions.py | 23 ++- 25 files changed, 508 insertions(+), 635 deletions(-) diff --git a/README.md b/README.md index b39325ca..7e76ccde 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ def test_list_type(): - [元组](src/data_types/test_tuples.py) - [集合](src/data_types/test_sets.py)及其方法 - [字典](src/data_types/test_dictionaries.py) - - [Type Casting](src/data_types/test_type_casting.py) + - [类型转换](src/data_types/test_type_casting.py) 4. **控制** - [if](src/control_flow/test_if.py) - [for](src/control_flow/test_for.py) (以及 `range()` 函数) diff --git a/src/classes/test_class_definition.py b/src/classes/test_class_definition.py index 9251c60e..3c81eee0 100644 --- a/src/classes/test_class_definition.py +++ b/src/classes/test_class_definition.py @@ -1,45 +1,40 @@ -"""Class Definition Syntax. +"""类定义的语法。 @see: https://docs.python.org/3/tutorial/classes.html -Python is an object oriented programming language. -Almost everything in Python is an object, with its properties and methods. -A Class is like an object constructor, or a "blueprint" for creating objects. +Python 是一种面向对象的编程语言。 +Python 中的几乎所有东西都是对象,包括它的属性和方法。 +类就像一个对象构造函数,或者创建对象的“蓝图”。 """ def test_class_definition(): - """Class definition.""" + """类定义""" - # Class definitions, like function definitions (def statements) must be executed before they - # have any effect. (You could conceivably place a class definition in a branch of an if - # statement, or inside a function.) + # 类定义,就像函数定义(def语句)一样,必须在它们生效之前执行。(可以将类定义放在if语句的分支中,或者函数中。) class GreetingClass: - """Example of the class definition + """类定义的示例 - This class contains two public methods and doesn't contain constructor. + 该类包含两个公共方法,不包含构造函数。 """ name = 'user' def say_hello(self): - """Class method.""" - # The self parameter is a reference to the class itself, and is used to access variables - # that belongs to the class. It does not have to be named self , you can call it - # whatever you like, but it has to be the first parameter of any function in the class. + """类方法""" + # self 参数是对类本身的引用,用于访问属于类的变量。 + # 它不一定是self,你可以随便叫它什么,但它必须是类中任何函数的第一个参数。 return 'Hello ' + self.name def say_goodbye(self): """Class method.""" return 'Goodbye ' + self.name - # When a class definition is entered, a new namespace is created, and used as the local scope — - # thus, all assignments to local variables go into this new namespace. In particular, function - # definitions bind the name of the new function here. + # 当输入一个类定义时,将创建一个新的命名空间,并将其用作局部作用域,所有对局部变量的赋值都将进入这个新的命名空间。 + # 特别是,函数定义在这里绑定了新函数的名称。 - # Class instantiation uses function notation. Just pretend that the class object is a - # parameterless function that returns a new instance of the class. For example the following - # code will creates a new instance of the class and assigns this object to the local variable. + # 类实例化使用函数表示法。 只需假设类对象是一个返回类的新实例的无参数函数。 + # 例如,下面的代码将创建一个类的新实例,并将该对象赋值给局部变量。 greeter = GreetingClass() assert greeter.say_hello() == 'Hello user' diff --git a/src/classes/test_class_objects.py b/src/classes/test_class_objects.py index 2d5a4cdb..886442c4 100644 --- a/src/classes/test_class_objects.py +++ b/src/classes/test_class_objects.py @@ -1,67 +1,62 @@ -"""Class Definition Syntax. +"""类定义的语法. @see: https://docs.python.org/3/tutorial/classes.html#class-objects -After defining the class attributes to a class, the class object can be created by assigning the -object to a variable. The created object would have instance attributes associated with it. +定义了类的类属性后,可以通过将对象赋值给变量来创建类对象。创建的对象将具有与其关联的实例属性。 """ def test_class_objects(): - """Class Objects. + """类对象。 - Class objects support two kinds of operations: - - attribute references - - instantiation. + 类对象支持两种操作: + - 属性引用 + - 实例化 """ - # ATTRIBUTE REFERENCES use the standard syntax used for all attribute references in - # Python: obj.name. Valid attribute names are all the names that were in the class’s namespace - # when the class object was created. For class MyCounter the following references are valid - # attribute references: + # 属性引用使用Python中用于所有属性引用的标准语法: obj.name. + # 有效的属性名是创建类对象时类的命名空间中的所有名称。 + # 对于MyCounter类,以下引用是有效的属性引用: class ComplexNumber: - """Example of the complex numbers class""" + """复数类的例子""" real = 0 imaginary = 0 def get_real(self): - """Return real part of complex number.""" + """返回复数的实部。""" return self.real def get_imaginary(self): - """Return imaginary part of complex number.""" + """返回复数的虚部。""" return self.imaginary assert ComplexNumber.real == 0 - # __doc__ is also a valid attribute, returning the docstring belonging to the class - assert ComplexNumber.__doc__ == 'Example of the complex numbers class' + # __doc__ 也是一个有效的属性,返回属于类的文档字符串 + assert ComplexNumber.__doc__ == '复数类的例子' - # Class attributes can also be assigned to, so you can change the value of - # ComplexNumber.counter by assignment. + # 类属性也可以被赋值,因此可以更改 ComplexNumber 的值。计数器的任务。 ComplexNumber.real = 10 assert ComplexNumber.real == 10 - # CLASS INSTANTIATION uses function notation. Just pretend that the class object is a - # parameterless function that returns a new instance of the class. For example - # (assuming the above class): + # 类实例化使用函数表示法。只需假设类对象是一个返回类的新实例的无参数函数。例如(假设上面的类): complex_number = ComplexNumber() assert complex_number.real == 10 assert complex_number.get_real() == 10 - # Let's change counter default value back. + # 让我们把计数器的默认值改回来。 ComplexNumber.real = 10 assert ComplexNumber.real == 10 - # The instantiation operation (“calling” a class object) creates an empty object. Many classes - # like to create objects with instances customized to a specific initial state. Therefore a - # class may define a special method named __init__(), like this: + # 实例化操作(“调用”类对象)创建一个空对象。许多类喜欢创建具有自定义到特定初始状态的实例的对象。 + # 因此,类可以定义一个名为__init__()的特殊方法,像这样: class ComplexNumberWithConstructor: - """Example of the class with constructor""" + """带有构造函数的类示例""" + def __init__(self, real_part, imaginary_part): self.real = real_part self.imaginary = imaginary_part diff --git a/src/control_flow/test_break.py b/src/control_flow/test_break.py index 42e7faa3..331f3148 100644 --- a/src/control_flow/test_break.py +++ b/src/control_flow/test_break.py @@ -1,25 +1,25 @@ -"""BREAK statement +"""break 语句 @see: https://docs.python.org/3/tutorial/controlflow.html -The break statement, like in C, breaks out of the innermost enclosing "for" or "while" loop. +break语句,就像在C中一样,打破了最内层的“for”或“while”循环。 """ def test_break_statement(): - """BREAK statement""" + """break 语句""" - # Let's terminate the loop in case if we've found the number we need in a range from 0 to 100. + # 如果我们在0到100的范围内找到了需要的数字,我们就终止循环。 number_to_be_found = 42 - # This variable will record how many time we've entered the "for" loop. + # 这个变量将记录我们输入“for”循环的次数。 number_of_iterations = 0 for number in range(100): if number == number_to_be_found: - # Break here and don't continue the loop. + # 在这里中断,不要继续循环。 break else: number_of_iterations += 1 - # We need to make sure that break statement has terminated the loop once it found the number. + # 我们需要确保break语句一旦找到编号就终止了循环。 assert number_of_iterations == 42 diff --git a/src/control_flow/test_continue.py b/src/control_flow/test_continue.py index 23c015bd..28b872df 100644 --- a/src/control_flow/test_continue.py +++ b/src/control_flow/test_continue.py @@ -1,26 +1,24 @@ -"""CONTINUE statement +"""continue 语句 @see: https://docs.python.org/3/tutorial/controlflow.html -The continue statement is borrowed from C, continues with the next iteration of the loop. +continue 语句借用自C语言,继续循环的下一个迭代。 """ def test_continue_statement(): - """CONTINUE statement in FOR loop""" + """FOR 环中的 CONTINUE 语句""" - # Let's - - # This list will contain only even numbers from the range. + # 这个列表将只包含范围中的偶数。 even_numbers = [] - # This list will contain every other numbers (in this case - ods). + # 这个列表将包含所有其他数字(在本例中是ods)。 rest_of_the_numbers = [] for number in range(0, 10): - # Check if remainder after division is zero (which would mean that number is even). + # 检查除法后余数是否为零(这意味着该数是偶数)。 if number % 2 == 0: even_numbers.append(number) - # Stop current loop iteration and go to the next one immediately. + # 停止当前循环迭代并立即转到下一个。 continue rest_of_the_numbers.append(number) diff --git a/src/control_flow/test_for.py b/src/control_flow/test_for.py index 3c830d7f..9df6f87d 100644 --- a/src/control_flow/test_for.py +++ b/src/control_flow/test_for.py @@ -24,23 +24,18 @@ def test_for_statement(): # "defenestrate" 长度是 12 assert words_length == (3 + 6 + 12) - # If you need to modify the sequence you are iterating over while inside the loop - # (for example to duplicate selected items), it is recommended that you first make a copy. - # Iterating over a sequence does not implicitly make a copy. The slice notation makes this - # especially convenient: - for word in words[:]: # Loop over a slice copy of the entire list. + # 如果您需要修改在循环内部迭代的序列 (例如,复制选定项),建议您先复印一份。 + # 在序列上迭代不会隐式地生成副本。 切片表示法使得这特别方便: + for word in words[:]: # 循环遍历整个列表的切片副本。 if len(word) > 6: words.insert(0, word) - print(words) - - # Otherwise with for w in words:, the example would attempt to create an infinite list, - # inserting defenestrate over and over again. + # 否则,这个例子将尝试创建一个无限列表,并反复插入defenestrate。 assert words == ['defenestrate', 'cat', 'window', 'defenestrate'] - # If you do need to iterate over a sequence of numbers, the built-in function range() comes in - # handy. It generates arithmetic progressions: + # 如果确实需要迭代一个数字序列,那么内置函数 range() 可以派上用场。 + # 它生成等差级数: iterated_numbers = [] for number in range(5): @@ -48,7 +43,7 @@ def test_for_statement(): assert iterated_numbers == [0, 1, 2, 3, 4] - # To iterate over the indices of a sequence, you can combine range() and len() as follows: + # 要遍历序列的索引,你可以组合 range() 和 len() 如下: words = ['Mary', 'had', 'a', 'little', 'lamb'] concatenated_string = '' @@ -58,7 +53,7 @@ def test_for_statement(): assert concatenated_string == 'Mary had a little lamb ' - # Or simply use enumerate(). + # 或者简单地使用 enumerate()。 concatenated_string = '' for word_index, word in enumerate(words): @@ -66,8 +61,7 @@ def test_for_statement(): assert concatenated_string == 'Mary had a little lamb ' - # When looping through dictionaries, the key and corresponding value can be retrieved at the - # same time using the items() method. + # 在遍历字典时,可以使用 items() 方法同时检索键和相应的值。 knights_names = [] knights_properties = [] @@ -79,8 +73,7 @@ def test_for_statement(): assert knights_names == ['gallahad', 'robin'] assert knights_properties == ['the pure', 'the brave'] - # When looping through a sequence, the position index and corresponding value can be retrieved - # at the same time using the enumerate() function + # 当循环遍历一个序列时,可以使用 enumerate() 函数同时检索位置索引和相应的值 indices = [] values = [] for index, value in enumerate(['tic', 'tac', 'toe']): @@ -90,8 +83,7 @@ def test_for_statement(): assert indices == [0, 1, 2] assert values == ['tic', 'tac', 'toe'] - # To loop over two or more sequences at the same time, the entries can be paired with - # the zip() function. + # 要同时循环两个或多个序列,可以将条目与 zip() 函数配对。 questions = ['name', 'quest', 'favorite color'] answers = ['lancelot', 'the holy grail', 'blue'] combinations = [] @@ -109,25 +101,20 @@ def test_for_statement(): def test_range_function(): """Range function - If you do need to iterate over a sequence of numbers, the built-in function range() comes in - handy. It generates arithmetic progressions. + 如果确实需要迭代一个数字序列,那么内置函数 range() 可以派上用场。 + 它产生等差级数。 - In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. - It is an object which returns the successive items of the desired sequence when you iterate - over it, but it doesn’t really make the list, thus saving space. + range() 返回的对象在很多方面都表现得像一个列表,但实际上它不是。 + 它是一个在迭代时返回所需序列的连续项的对象,但它并不真正构成列表,因此节省了空间。 - We say such an object is iterable, that is, suitable as a target for functions and constructs - that expect something from which they can obtain successive items until the supply is exhausted. - We have seen that the for statement is such an iterator. The function list() is another; it - creates lists from iterables: + 我们说这样的对象是可迭代的,也就是说,适合作为函数和构造的目标他们期望能得到一些连续的东西,直到供应耗尽。 + 我们已经看到for语句就是这样一个迭代器。函数list()是另一个; 它从可迭代对象中创建列表: """ assert list(range(5)) == [0, 1, 2, 3, 4] - # The given end point is never part of the generated sequence; range(10) generates 10 values, - # the legal indices for items of a sequence of length 10. It is possible to let the range start - # at another number, or to specify a different increment (even negative; sometimes this is - # called the ‘step’): + # 给定的终点从来不是生成序列的一部分; range(10) 生成10个值,即长度为10的序列的合法索引。 + # 可以让范围从另一个数字开始,或指定不同的增量 (甚至负数; 有时这被称为‘step’): assert list(range(5, 10)) == [5, 6, 7, 8, 9] assert list(range(0, 10, 3)) == [0, 3, 6, 9] diff --git a/src/control_flow/test_if.py b/src/control_flow/test_if.py index d512267d..3c46ffcc 100644 --- a/src/control_flow/test_if.py +++ b/src/control_flow/test_if.py @@ -1,12 +1,11 @@ -"""IF statement +"""IF 语句 @see: https://docs.python.org/3/tutorial/controlflow.html -There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is -short for ‘else if’, and is useful to avoid excessive indentation. +可以有零个或多个elif部分,else部分是可选的。 +关键字' elif '是' else if '的缩写,用于避免过度缩进。 -An if … elif … elif … sequence is a substitute for the switch or case statements found -in other languages. +在其他语言中 switch ... case 语句是 if … elif … elif … 替代品 """ diff --git a/src/control_flow/test_try.py b/src/control_flow/test_try.py index fed06f59..e06f63d5 100644 --- a/src/control_flow/test_try.py +++ b/src/control_flow/test_try.py @@ -1,22 +1,21 @@ -"""TRY statement +"""try 语句 @see: https://www.w3schools.com/python/python_try_except.asp -"try" statement is used for exception handling. -When an error occurs, or exception as we call it, Python will normally stop and generate an error -message. These exceptions can be handled using the try statement. +"try" 语句被用于异常处理. +当出现错误或我们所说的异常时,Python通常会停止并生成错误消息。这些异常可以使用try语句来处理。 -The "try" block lets you test a block of code for errors. -The "except" block lets you handle the error. -The "else" block lets you execute the code if no errors were raised. -The "finally" block lets you execute code, regardless of the result of the try- and except blocks. +“try” 块允许您测试代码块的错误。 +“except” 块允许您处理错误。 +"else" 块允许您在没有引发错误的情况下执行代码。 +“finally” 块允许您执行代码,而不管try的结果如何——除了块之外。 """ def test_try(): """TRY statement""" - # The try block will generate an error, because x is not defined: + # try块将产生一个错误,因为 not_existing_variable 没有定义: exception_has_been_caught = False try: @@ -27,8 +26,7 @@ def test_try(): assert exception_has_been_caught - # You can define as many exception blocks as you want, e.g. if you want to execute a special - # block of code for a special kind of error: + # 你可以定义任意多的异常块,例如,如果你想为一个特殊的错误执行一个特殊的代码块: exception_message = '' try: @@ -39,8 +37,7 @@ def test_try(): assert exception_message == 'Variable is not defined' - # You can use the else keyword to define a block of code to be executed - # if no errors were raised. + # 如果未引发错误,可以使用else关键字定义要执行的代码块。 message = '' # pylint: disable=broad-except try: @@ -52,8 +49,7 @@ def test_try(): assert message == 'Success.Nothing went wrong.' - # The finally block, if specified, will be executed regardless if the try block raises an - # error or not. + # 如果指定了 finally 块,则无论try块是否引发错误都将执行。 message = '' try: # pylint: undefined-variable diff --git a/src/control_flow/test_while.py b/src/control_flow/test_while.py index 4bc58028..e3571d88 100644 --- a/src/control_flow/test_while.py +++ b/src/control_flow/test_while.py @@ -1,23 +1,21 @@ -"""WHILE statement +"""while 语句 @see: https://docs.python.org/3/tutorial/controlflow.html @see: https://docs.python.org/3/reference/compound_stmts.html#the-while-statement -The while loop executes as long as the condition remains true. In Python, like in C, any -non-zero integer value is true; zero is false. The condition may also be a string or list -value, in fact any sequence; anything with a non-zero length is true, empty sequences are -false. +只要条件保持为真,while循环就会执行。 +在Python中,像在C中一样,任何非零整数值都为真;零是错误的。 +条件也可以是字符串或列表值,实际上可以是任何序列;任何长度非零的都为真,空序列为假。 -The test used in the example is a simple comparison. The standard comparison operators are -written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or -equal to), >= (greater than or equal to) and != (not equal to). +示例中使用的测试是一个简单的比较。 +标准比较操作符的写法与C中相同:<(小于)、>(大于)、==(等于)、<=(小于或等于)、>=(大于或等于)和!=(不等于)。 """ def test_while_statement(): """WHILE statement""" - # Let's raise the number to certain power using while loop. + # 让我们用 while 循环将这个数提高到某个幂。 number = 2 power = 5 diff --git a/src/data_types/test_dictionaries.py b/src/data_types/test_dictionaries.py index da3b9cc8..5c98b5bf 100644 --- a/src/data_types/test_dictionaries.py +++ b/src/data_types/test_dictionaries.py @@ -1,23 +1,19 @@ -"""Dictionaries. +"""字典. @see: https://docs.python.org/3/tutorial/datastructures.html#dictionaries @see: https://www.w3schools.com/python/python_dictionaries.asp -A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are -written with curly brackets, and they have keys and values. - -Dictionaries are sometimes found in other languages as “associative memories” or “associative -arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by -keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used -as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object -either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since -lists can be modified in place using index assignments, slice assignments, or methods like append() -and extend(). - -It is best to think of a dictionary as a set of key: value pairs, with the requirement that the -keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. -Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs -to the dictionary; this is also the way dictionaries are written on output. +字典是无序的、可变的和有索引的集合。 +在 Python 中,字典是用大括号写的,它们有键和值。 + +在其他语言中,词典有时被称为“联想记忆”或“联想记忆”数组”。 +与序列(由一系列数字建立索引)不同,字典通过键建立索引,键可以是任何不可变类型; +字符串和数字总是可以作为键. 如果元组只包含字符串、数字或元组,则可以用作键;如果一个元组包含任何可变对象它不能直接或间接地作为键使用. +不能将列表用作键,因为可以使用索引赋值、切片赋值或 append() 和 extend() 等方法在适当的位置修改列表。 + +最好把字典看作是一组键: 值对, 有了这个要求键是唯一的(在一个字典中)。 +一对大括号创建一个空字典:{}。 +在花括号中放置一个逗号分隔的键:值对列表,将初始键:值对添加到字典中;这也是在输出上编写字典的方式。 """ @@ -32,47 +28,44 @@ def test_dictionary(): assert isinstance(fruits_dictionary, dict) - # You may access set elements by keys. + # 你可以通过键来访问集合元素。 assert fruits_dictionary['apple'] == 'green' assert fruits_dictionary['banana'] == 'yellow' assert fruits_dictionary['cherry'] == 'red' - # To check whether a single key is in the dictionary, use the in keyword. + # 若要检查字典中是否有单个键,请使用in关键字。 assert 'apple' in fruits_dictionary assert 'pineapple' not in fruits_dictionary - # Change the apple color to "red". + # 改变苹果的颜色为“红色”。 fruits_dictionary['apple'] = 'red' - # Add new key/value pair to the dictionary + # 向字典中添加新的键值对 fruits_dictionary['pineapple'] = 'yellow' assert fruits_dictionary['pineapple'] == 'yellow' - # Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, - # in insertion order (if you want it sorted, just use sorted(d) instead). + # 对一个字典执行list(d)将返回一个包含该字典中使用的所有键的列表,按插入顺序(如果您想要对其排序,只需使用sorted(d))。 assert list(fruits_dictionary) == ['cherry', 'apple', 'banana', 'pineapple'] assert sorted(fruits_dictionary) == ['apple', 'banana', 'cherry', 'pineapple'] - # It is also possible to delete a key:value pair with del. + # 也可以用del删除键值对。 del fruits_dictionary['pineapple'] assert list(fruits_dictionary) == ['cherry', 'apple', 'banana'] - # The dict() constructor builds dictionaries directly from sequences of key-value pairs. + # dict()构造函数直接从键-值对序列构建字典。 dictionary_via_constructor = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) assert dictionary_via_constructor['sape'] == 4139 assert dictionary_via_constructor['guido'] == 4127 assert dictionary_via_constructor['jack'] == 4098 - # In addition, dict comprehensions can be used to create dictionaries from arbitrary key - # and value expressions: - dictionary_via_expression = {x: x**2 for x in (2, 4, 6)} + # 此外,字典推导式可以用于从任意键和值表达式创建字典: + dictionary_via_expression = {x: x ** 2 for x in (2, 4, 6)} assert dictionary_via_expression[2] == 4 assert dictionary_via_expression[4] == 16 assert dictionary_via_expression[6] == 36 - # When the keys are simple strings, it is sometimes easier to specify pairs using - # keyword arguments. + # 当键是简单字符串时,使用关键字参数指定键对有时会更容易。 dictionary_for_string_keys = dict(sape=4139, guido=4127, jack=4098) assert dictionary_for_string_keys['sape'] == 4139 assert dictionary_for_string_keys['guido'] == 4127 diff --git a/src/data_types/test_lists.py b/src/data_types/test_lists.py index 33ffdbe9..3d53ec67 100644 --- a/src/data_types/test_lists.py +++ b/src/data_types/test_lists.py @@ -1,72 +1,66 @@ -"""Lists. +"""列表 # @see: https://www.learnpython.org/en/Lists # @see: https://docs.python.org/3/tutorial/introduction.html # @ee: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists -Python knows a number of compound data types, used to group together -other values. The most versatile is the list, which can be written as a -list of comma-separated values (items) between square brackets. Lists -might contain items of different types, but usually the items all have -the same type. +Python 知道许多用于组合的复合数据类型其他值。 +最通用的是列表,可以写成 a 方括号之间用逗号分隔的值(项)列表。 +列表可能包含不同类型的项,但通常所有项都有相同的类型. """ import pytest def test_list_type(): - """List type.""" + """列表类型.""" - # Lists are very similar to arrays. They can contain any type of variable, and they can contain - # as many variables as you wish. Lists can also be iterated over in a very simple manner. - # Here is an example of how to build a list. + # 列表非常类似于数组. 它们可以包含任何类型的变量,并且可以包含任意多的变量. + # 列表也可以以一种非常简单的方式迭代. + # 下面是一个如何构建列表的示例。 squares = [1, 4, 9, 16, 25] assert isinstance(squares, list) - # Like strings (and all other built-in sequence type), lists can be - # indexed and sliced: - assert squares[0] == 1 # indexing returns the item + # 和字符串(以及所有其他内置序列类型)一样,列表也可以被索引和切片: + assert squares[0] == 1 # 索引返回项 assert squares[-1] == 25 - assert squares[-3:] == [9, 16, 25] # slicing returns a new list + assert squares[-3:] == [9, 16, 25] # slice 返回一个新列表 - # All slice operations return a new list containing the requested elements. - # This means that the following slice returns a new (shallow) copy of - # the list: + # 所有切片操作都返回一个包含所请求元素的新列表。 + # 这意味着下面的切片返回列表的一个新(浅)副本: assert squares[:] == [1, 4, 9, 16, 25] - # Lists also support operations like concatenation: + # 列表也支持像连接这样的操作: assert squares + [36, 49, 64, 81, 100] == [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] - # Unlike strings, which are immutable, lists are a mutable type, i.e. it - # is possible to change their content: - cubes = [1, 8, 27, 65, 125] # something's wrong here, the cube of 4 is 64! - cubes[3] = 64 # replace the wrong value + # 与不可变的字符串不同,列表是一种可变类型。 + # 可以改变它们的内容: + cubes = [1, 8, 27, 65, 125] # 这里有问题,4的 3 次方是64! + cubes[3] = 64 # 替换错误的值 assert cubes == [1, 8, 27, 64, 125] - # You can also add new items at the end of the list, by using - # the append() method - cubes.append(216) # add the cube of 6 - cubes.append(7 ** 3) # and the cube of 7 + # 还可以使用append()方法在列表末尾添加新项 + cubes.append(216) # 添加 6的立方 + cubes.append(7 ** 3) # 添加 7的立方 assert cubes == [1, 8, 27, 64, 125, 216, 343] - # Assignment to slices is also possible, and this can even change the size - # of the list or clear it entirely: + # 也可以给切片赋值,这甚至可以改变列表的大小或完全清除它: letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] - letters[2:5] = ['C', 'D', 'E'] # replace some values + letters[2:5] = ['C', 'D', 'E'] # 替换一些值 assert letters == ['a', 'b', 'C', 'D', 'E', 'f', 'g'] - letters[2:5] = [] # now remove them + letters[2:5] = [] # 现在删除它们 assert letters == ['a', 'b', 'f', 'g'] - # clear the list by replacing all the elements with an empty list + # 通过将所有元素替换为空列表来清除列表 letters[:] = [] assert letters == [] - # The built-in function len() also applies to lists + # 内置函数len()也适用于列表 letters = ['a', 'b', 'c', 'd'] assert len(letters) == 4 - # It is possible to nest lists (create lists containing other lists), - # for example: + # 可以嵌套列表(创建包含其他列表的列表), + # 例如: list_of_chars = ['a', 'b', 'c'] list_of_numbers = [1, 2, 3] mixed_list = [list_of_chars, list_of_numbers] @@ -76,19 +70,19 @@ def test_list_type(): def test_list_methods(): - """Test list methods.""" + """测试列表的方法。""" fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] # list.append(x) - # Add an item to the end of the list. - # Equivalent to a[len(a):] = [x]. + # 将一个项目添加到列表的末尾。 + # 相当于 a[len(a):] = [x]. fruits.append('grape') assert fruits == ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana', 'grape'] # list.remove(x) - # Remove the first item from the list whose value is equal to x. - # It raises a ValueError if there is no such item. + # 从列表中删除值为x的第一项. + # 如果没有这样的项,它将引发ValueError。 fruits.remove('grape') assert fruits == ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] @@ -96,38 +90,37 @@ def test_list_methods(): fruits.remove('not existing element') # list.insert(i, x) - # Insert an item at a given position. The first argument is the index of the element - # before which to insert, so a.insert(0, x) inserts at the front of the list, - # and a.insert(len(a), x) is equivalent to a.append(x). + # 在给定位置插入一项。 + # 第一个参数是要插入的元素的索引,所以 a.insert(0, x) 插入到列表的前面,而 a.insert(len(a), x) 等价于 a.append(x)。 fruits.insert(0, 'grape') assert fruits == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] # list.index(x[, start[, end]]) - # Return zero-based index in the list of the first item whose value is equal to x. - # Raises a ValueError if there is no such item. - # The optional arguments start and end are interpreted as in the slice notation and are used - # to limit the search to a particular subsequence of the list. The returned index is computed - # relative to the beginning of the full sequence rather than the start argument. + # 返回值为x的第一个项的列表中从0开始的索引。 + # 如果没有这样的项则引发ValueError。 + # 可选参数 start 和 end 被解释为切片表示法,用于将搜索限制为列表的特定子序列。 + # 返回计算的索引 + # 相对于整个序列的开始,而不是start参数。 assert fruits.index('grape') == 0 assert fruits.index('orange') == 1 assert fruits.index('banana') == 4 - assert fruits.index('banana', 5) == 7 # Find next banana starting a position 5 + assert fruits.index('banana', 5) == 7 # 找到下一个 banana 开始位置 5 with pytest.raises(Exception): fruits.index('not existing element') # list.count(x) - # Return the number of times x appears in the list. + # 返回 x 出现在列表中的次数。 assert fruits.count('tangerine') == 0 assert fruits.count('banana') == 2 # list.copy() - # Return a shallow copy of the list. Equivalent to a[:]. + # 返回列表的浅拷贝。 相当于 a[:]. fruits_copy = fruits.copy() assert fruits_copy == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] # list.reverse() - # Reverse the elements of the list in place. + # 将列表中的元素反向排列。 fruits_copy.reverse() assert fruits_copy == [ 'banana', @@ -141,8 +134,7 @@ def test_list_methods(): ] # list.sort(key=None, reverse=False) - # Sort the items of the list in place (the arguments can be used for sort customization, - # see sorted() for their explanation). + # 对列表中的项进行适当排序(参数可用于排序定制,请参阅 sorted() 了解它们的解释)。 fruits_copy.sort() assert fruits_copy == [ 'apple', @@ -156,27 +148,23 @@ def test_list_methods(): ] # list.pop([i]) - # Remove the item at the given position in the list, and return it. If no index is specified, - # a.pop() removes and returns the last item in the list. (The square brackets around the i in - # the method signature denote that the parameter is optional, not that you should type square - # brackets at that position.) + # 删除列表中给定位置的项,并返回它。如果没有指定索引,a.pop()将删除并返回列表中的最后一项。 + # (方法签名中i周围的方括号表示参数是可选的,而不是在那个位置输入方括号。) assert fruits == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] assert fruits.pop() == 'banana' assert fruits == ['grape', 'orange', 'apple', 'pear', 'banana', 'kiwi', 'apple'] # list.clear() - # Remove all items from the list. Equivalent to del a[:]. + # 从列表中删除所有项目。 相当于 del a[:]. fruits.clear() assert fruits == [] def test_del_statement(): - """The del statement + """del 语法 - There is a way to remove an item from a list given its index instead of its value: the del - statement. This differs from the pop() method which returns a value. The del statement can also - be used to remove slices from a list or clear the entire list (which we did earlier by - assignment of an empty list to the slice). + 有一种方法可以从列表中删除给定索引而不是值的项: del. + 这与有返回值的 pop()方法不同。 del语句还可以用于从列表中删除片或清除整个列表 (我们之前是通过给切片赋一个空列表来做的). """ numbers = [-1, 1, 66.25, 333, 333, 1234.5] @@ -190,48 +178,45 @@ def test_del_statement(): del numbers[:] assert numbers == [] - # del can also be used to delete entire variables: + # del 也可以用来删除整个变量: del numbers with pytest.raises(Exception): - # Referencing the name a hereafter is an error (at least until another - # value is assigned to it). + # 之后引用名称 numbers 是错误的 (至少在给它赋值之前是这样). assert numbers == [] # noqa: F821 def test_list_comprehensions(): - """List Comprehensions. + """列表推导式. - List comprehensions provide a concise way to create lists. Common applications are to make new - lists where each element is the result of some operations applied to each member of another - sequence or iterable, or to create a subsequence of those elements that satisfy a certain - condition. + 列表推导式提供了一种创建列表的简明方法。 常见的应用是使新列出每个元素是应用于另一个元素的每个成员的某些操作的结果序列或可迭代的, + 或创建满足一定条件的那些元素的子序列条件。 - A list comprehension consists of brackets containing an expression followed by a for clause, - then zero or more for or if clauses. The result will be a new list resulting from evaluating - the expression in the context of the for and if clauses which follow it. + 列表推导式由括号组成,括号中包含一个表达式,后面跟着一个 for 子句,然后零个或多个 for 或 if 子句。 + 结果将是一个新的列表,它是在表达式后面的 for 和 if 子句的上下文中对表达式求值而得到的。 """ - # For example, assume we want to create a list of squares, like: + # 例如,假设我们想要创建一个正方形列表, + # 请注意,这将创建(或覆盖)一个名为“number”的变量,该变量在循环完成后仍然存在。 + # 例如: squares = [] for number in range(10): squares.append(number ** 2) assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - # Note that this creates (or overwrites) a variable named "number" that still exists after - # the loop completes. We can calculate the list of squares without any side effects using: + # 我们可以在没有任何副作用的情况下计算方块列表: squares = list(map(lambda x: x ** 2, range(10))) assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - # or, equivalently (which is more concise and readable): + # 或者,同样的(更简洁易读): squares = [x ** 2 for x in range(10)] assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] - # For example, this listcomp combines the elements of two lists if they are not equal. + # 例如,如果两个列表的元素不相等,这个 listcomp 将组合它们。 combinations = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y] assert combinations == [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] - # and it’s equivalent to: + # 它等价于 combinations = [] for first_number in [1, 2, 3]: for second_number in [3, 1, 4]: @@ -240,57 +225,54 @@ def test_list_comprehensions(): assert combinations == [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] - # Note how the order of the for and if statements is the same in both these snippets. + # 注意,这两个代码片段中的for和if语句的顺序是相同的. - # If the expression is a tuple (e.g. the (x, y) in the previous example), - # it must be parenthesized. + # 如果表达式是一个元组(例如前面例子中的(x, y)),则必须用圆括号括起来。 - # Let's see some more examples: + # 让我们来看更多的例子: vector = [-4, -2, 0, 2, 4] - # Create a new list with the values doubled. + # 创建一个值翻倍的新列表。 doubled_vector = [x * 2 for x in vector] assert doubled_vector == [-8, -4, 0, 4, 8] - # Filter the list to exclude negative numbers. + # 过滤列表以排除负数。 positive_vector = [x for x in vector if x >= 0] assert positive_vector == [0, 2, 4] - # Apply a function to all the elements. + # 对所有元素应用一个函数。 abs_vector = [abs(x) for x in vector] assert abs_vector == [4, 2, 0, 2, 4] - # Call a method on each element. + # 对每个元素调用一个方法。 fresh_fruit = [' banana', ' loganberry ', 'passion fruit '] clean_fresh_fruit = [weapon.strip() for weapon in fresh_fruit] assert clean_fresh_fruit == ['banana', 'loganberry', 'passion fruit'] - # Create a list of 2-tuples like (number, square). + # 创建一个2元组列表,如(number, square). square_tuples = [(x, x ** 2) for x in range(6)] assert square_tuples == [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] - # Flatten a list using a listcomp with two 'for'. + # 使用带有两个 for 的列表组合使列表变平. vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flatten_vector = [num for elem in vector for num in elem] assert flatten_vector == [1, 2, 3, 4, 5, 6, 7, 8, 9] def test_nested_list_comprehensions(): - """Nested List Comprehensions - - The initial expression in a list comprehension can be any arbitrary expression, including - another list comprehension. + """嵌套列表推导式1 + 列表推导式中的初始表达式可以是任意表达式,包括另一个corrrmprehension列表。 """ - # Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4: + # 考虑下面这个3x4矩阵的例子,它是一个由3个长度为4的列表组成的列表: matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] - # The following list comprehension will transpose rows and columns: + # 下面的列表推导式将对行和列进行转置: transposed_matrix = [[row[i] for row in matrix] for i in range(4)] assert transposed_matrix == [ [1, 5, 9], @@ -299,8 +281,7 @@ def test_nested_list_comprehensions(): [4, 8, 12], ] - # As we saw in the previous section, the nested listcomp is evaluated in the context of the - # for that follows it, so this example is equivalent to: + # 正如我们在前一节中看到的,嵌套的listcomp是在它后面的for上下文中求值的, 所以这个例子相当于: transposed = [] for i in range(4): transposed.append([row[i] for row in matrix]) @@ -312,10 +293,10 @@ def test_nested_list_comprehensions(): [4, 8, 12], ] - # which, in turn, is the same as: + # 反过来,也就是: transposed = [] for i in range(4): - # the following 3 lines implement the nested listcomp + # 下面的3行实现了嵌套的listcomp transposed_row = [] for row in matrix: transposed_row.append(row[i]) @@ -328,8 +309,8 @@ def test_nested_list_comprehensions(): [4, 8, 12], ] - # In the real world, you should prefer built-in functions to complex flow statements. - # The zip() function would do a great job for this use case: + # 在现实世界中,您应该更喜欢内置函数而不是复杂的流语句。 + # zip()函数可以很好地完成这个用例: assert list(zip(*matrix)) == [ (1, 5, 9), (2, 6, 10), diff --git a/src/data_types/test_sets.py b/src/data_types/test_sets.py index 1dfb1329..1f0505c4 100644 --- a/src/data_types/test_sets.py +++ b/src/data_types/test_sets.py @@ -1,13 +1,12 @@ -"""Sets. +""" Set. @see: https://www.w3schools.com/python/python_sets.asp @see: https://docs.python.org/3.7/tutorial/datastructures.html#sets -A set is a collection which is unordered and unindexed. -In Python sets are written with curly brackets. +set 是无序且无索引的集合。 +在 Python 中,集合是用花括号写的. -Set objects also support mathematical operations like union, intersection, difference, and -symmetric difference. +集合对象还支持数学运算,如并、交、差和对称差。 """ @@ -17,8 +16,8 @@ def test_sets(): assert isinstance(fruits_set, set) - # It is also possible to use the set() constructor to make a set. - # Note the double round-brackets + # 也可以使用set()构造函数来创建集合。 + # 注意双圆括号 fruits_set_via_constructor = set(("apple", "banana", "cherry")) assert isinstance(fruits_set_via_constructor, set) @@ -29,42 +28,42 @@ def test_set_methods(): fruits_set = {"apple", "banana", "cherry"} - # You may check if the item is in set by using "in" statement + # 你可以使用“in”语句检查项目是否已设置 assert "apple" in fruits_set assert "pineapple" not in fruits_set - # Use the len() method to return the number of items. + # 使用len()方法返回项的数量。 assert len(fruits_set) == 3 - # You can use the add() object method to add an item. + # 您可以使用add()对象方法来添加一个项目. fruits_set.add("pineapple") assert "pineapple" in fruits_set assert len(fruits_set) == 4 - # Use remove() method to remove an item. + # 使用remove()方法删除一个条目。 fruits_set.remove("pineapple") assert "pineapple" not in fruits_set assert len(fruits_set) == 3 - # Demonstrate set operations on unique letters from two word: + # 演示对两个单词中唯一字母的集合操作: first_char_set = set('abracadabra') second_char_set = set('alacazam') - assert first_char_set == {'a', 'r', 'b', 'c', 'd'} # unique letters in first word - assert second_char_set == {'a', 'l', 'c', 'z', 'm'} # unique letters in second word + assert first_char_set == {'a', 'r', 'b', 'c', 'd'} # 第一个单词的唯一字母 + assert second_char_set == {'a', 'l', 'c', 'z', 'm'} # 第二个单词中唯一的字母 - # Letters in first word but not in second. + # 字母在第一个单词中,但不在第二个单词中。 assert first_char_set - second_char_set == {'r', 'b', 'd'} - # Letters in first word or second word or both. + # 第一个单词或第二个单词或两个单词中的字母。 assert first_char_set | second_char_set == {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} - # Common letters in both words. + # 两个单词中常见的字母。 assert first_char_set & second_char_set == {'a', 'c'} - # Letters in first or second word but not both. + # 字母出现在第一个或第二个单词中,但不能同时出现在两个单词中。 assert first_char_set ^ second_char_set == {'r', 'd', 'b', 'm', 'z', 'l'} - # Similarly to list comprehensions, set comprehensions are also supported: + # 与列表推导式类似,集合推导式也支持: word = {char for char in 'abracadabra' if char not in 'abc'} assert word == {'r', 'd'} diff --git a/src/data_types/test_strings.py b/src/data_types/test_strings.py index 88dd708c..22f5b4c3 100644 --- a/src/data_types/test_strings.py +++ b/src/data_types/test_strings.py @@ -71,34 +71,32 @@ def test_string_type(): # 0 1 2 3 4 5 6 # -6 -5 -4 -3 -2 -1 - # Attempting to use an index that is too large will result in an error. + # 试图使用一个太大的索引将导致一个错误。 with pytest.raises(Exception): not_existing_character = word[42] assert not not_existing_character - # However, out of range slice indexes are handled gracefully when used - # for slicing: + # 但是,在使用范围外的片索引时,使用切片会得到很好的处理: assert word[4:42] == 'on' assert word[42:] == '' - # Python strings cannot be changed — they are immutable. Therefore, - # assigning to an indexed position in the string - # results in an error: + # Python字符串不能被改变——它们是不可变的。因此,对字符串中的索引位置赋值会导致错误: with pytest.raises(Exception): # pylint: disable=unsupported-assignment-operation word[0] = 'J' - # If you need a different string, you should create a new one: + # 如果您需要一个不同的字符串,您应该创建一个新的: assert 'J' + word[1:] == 'Jython' assert word[:2] + 'py' == 'Pypy' - # The built-in function len() returns the length of a string: + # 内置函数len()返回字符串的长度: characters = 'supercalifragilisticexpialidocious' assert len(characters) == 34 - # String literals can span multiple lines. One way is using triple-quotes: """...""" - # or '''...'''. End of lines are automatically included in the string, but it’s possible - # to prevent this by adding a \ at the end of the line. The following example: + # 字符串字面值可以跨多行。一种方法是使用三引号: """...""" 或 '''...'''. + # 字符串中自动包含行结束符,但可以通过在行结束符中添加\来防止这种情况。 + # + # 下面的例子: multi_line_string = '''\ First line Second line @@ -111,119 +109,111 @@ def test_string_type(): def test_string_operators(): - """Basic operations + """ 基本运算 - Strings can be concatenated (glued together) with the + operator, - and repeated with *: 3 times 'un', followed by 'ium' + 字符串可以用 + 操作符连接(粘在一起),并用 * 重复连接3次 'un',接着是'ium' """ assert 3 * 'un' + 'ium' == 'unununium' # 'Py' 'thon' - python = 'Py' 'thon' + python = 'Py''thon' assert python == 'Python' - # This feature is particularly useful when you want to break long strings: + # 当您想要中断长字符串时,这个特性特别有用: text = ( 'Put several strings within parentheses ' 'to have them joined together.' ) assert text == 'Put several strings within parentheses to have them joined together.' - # If you want to concatenate variables or a variable and a literal, use +: + # 如果你想要连接变量或者一个变量和一个字面值,使用+: prefix = 'Py' assert prefix + 'thon' == 'Python' def test_string_methods(): - """String methods""" + """字符串的方法""" hello_world_string = "Hello, World!" - # The strip() method removes any whitespace from the beginning or the end. + # strip()方法从开头或结尾删除任何空格. string_with_whitespaces = " Hello, World! " assert string_with_whitespaces.strip() == "Hello, World!" - # The len() method returns the length of a string. + # len()方法返回字符串的长度. assert len(hello_world_string) == 13 - # The lower() method returns the string in lower case. + # lower()方法返回小写的字符串. assert hello_world_string.lower() == 'hello, world!' - # The upper() method returns the string in upper case. + # upper()方法以大写形式返回字符串. assert hello_world_string.upper() == 'HELLO, WORLD!' - # The replace() method replaces a string with another string. + # replace()方法将一个字符串替换为另一个字符串. assert hello_world_string.replace('H', 'J') == 'Jello, World!' - # The split() method splits the string into substrings if it finds instances of the separator. + # 如果找到分隔符实例,split()方法将字符串分割成子字符串. assert hello_world_string.split(',') == ['Hello', ' World!'] - # Converts the first character to upper case + # 将第一个字符转换为大写 assert 'low letter at the beginning'.capitalize() == 'Low letter at the beginning' - # Returns the number of times a specified value occurs in a string. + # 返回指定值在字符串中出现的次数. assert 'low letter at the beginning'.count('t') == 4 - # Searches the string for a specified value and returns the position of where it was found. + # 在字符串中搜索指定的值并返回找到它的位置. assert 'Hello, welcome to my world'.find('welcome') == 7 - # Converts the first character of each word to upper case + # 将每个单词的第一个字符转换为大写 assert 'Welcome to my world'.title() == 'Welcome To My World' - # Returns a string where a specified value is replaced with a specified value. + # 返回一个字符串,其中指定的值被替换为指定的值。 assert 'I like bananas'.replace('bananas', 'apples') == 'I like apples' - # Joins the elements of an iterable to the end of the string. + # 将可迭代对象的元素连接到字符串的末尾. my_tuple = ('John', 'Peter', 'Vicky') assert ', '.join(my_tuple) == 'John, Peter, Vicky' - # Returns True if all characters in the string are upper case. + # 如果字符串中的所有字符都是大写,则返回True. assert 'ABC'.isupper() assert not 'AbC'.isupper() - # Check if all the characters in the text are letters. + # 检查文本中的所有字符是否都是字母. assert 'CompanyX'.isalpha() assert not 'Company 23'.isalpha() - # Returns True if all characters in the string are decimals. + # 如果字符串中的所有字符都是数字,则返回True. assert '1234'.isdecimal() assert not 'a21453'.isdecimal() def test_string_formatting(): - """String formatting. + """字符串格式化. - Often you’ll want more control over the formatting of your output than simply printing - space-separated values. There are several ways to format output + 通常情况下,比起简单地打印,您希望对输出的格式有更多的控制空格分隔的值。有几种方法可以格式化输出 """ - # To use formatted string literals, begin a string with f or F before the opening quotation - # mark or triple quotation mark. Inside this string, you can write a Python expression - # between { and } characters that can refer to variables or literal values. + # 若要使用格式化字符串字面值,请在字符串的开始引号或三引号之前以 F 或 f 开头。 + # 在这个字符串内部,你可以在 { and } 字符之间编写一个 Python 表达式,它可以引用变量或文字值。 year = 2018 event = 'conference' assert f'Results of the {year} {event}' == 'Results of the 2018 conference' - # The str.format() method of strings requires more manual effort. You’ll still use { and } to - # mark where a variable will be substituted and can provide detailed formatting directives, - # but you’ll also need to provide the information to be formatted. - yes_votes = 42_572_654 # equivalent of 42572654 - no_votes = 43_132_495 # equivalent of 43132495 + # 字符串的str.format()方法需要更多的手动操作。 您仍将使用{ and }来标记变量将被替换的位置,并可以提供详细的格式化指令, + # 但是您还需要提供要格式化的信息。 + yes_votes = 42_572_654 # 相当于 42572654 + no_votes = 43_132_495 # 相当于 43132495 percentage = yes_votes / (yes_votes + no_votes) assert '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage) == ' 42572654 YES votes 49.67%' - # When you don’t need fancy output but just want a quick display of some variables for debugging - # purposes, you can convert any value to a string with the repr() or str() functions. The str() - # function is meant to return representations of values which are fairly human-readable, while - # repr() is meant to generate representations which can be read by the interpreter (or will - # force a SyntaxError if there is no equivalent syntax). For objects which don’t have a - # particular representation for human consumption, str() will return the same value as repr(). - # Many values, such as numbers or structures like lists and dictionaries, have the same - # representation using either function. Strings, in particular, have two distinct - # representations. + # 当您不需要花哨的输出,而只想快速显示一些用于调试的变量时,可以使用repr()或str()函数将任何值转换为字符串。 + # str()函数的目的是返回值的表示,这些值是相当可读的, 而 repr() 的目的是生成解释器可以读取的表示(或者如果没有等效的语法,将强制SyntaxError)。 + # 对于没有特定表示供人类使用的对象,str()将返回与repr()相同的值。. + # 许多值,如数字或像列表和字典这样的结构,使用这两个函数都有相同的表示。 + # 特别是字符串,有两种不同的表示形式。 greeting = 'Hello, world.' first_num = 10 * 3.25 @@ -231,24 +221,19 @@ def test_string_formatting(): assert str(greeting) == 'Hello, world.' assert repr(greeting) == "'Hello, world.'" - assert str(1/7) == '0.14285714285714285' + assert str(1 / 7) == '0.14285714285714285' - # The argument to repr() may be any Python object: + # repr()的参数可以是任何Python对象: assert repr((first_num, second_num, ('spam', 'eggs'))) == "(32.5, 40000, ('spam', 'eggs'))" - # Formatted String Literals - - # Formatted string literals (also called f-strings for short) let you include the value of - # Python expressions inside a string by prefixing the string with f or F and writing - # expressions as {expression}. + # 格式化的字符串 - # An optional format specifier can follow the expression. This allows greater control over how - # the value is formatted. The following example rounds pi to three places after the decimal. + # 格式化字符串字面值(也简称f-strings)可以让你在字符串前加上f或f,并将表达式写成{expression},从而将 Python 表达式的值包含在字符串中。 + # 表达式后面可以有一个可选的格式说明符. 这允许对如何格式化值进行更大的控制. 下面的示例将圆周率四舍五入到小数点后三位。 pi_value = 3.14159 assert f'The value of pi is {pi_value:.3f}.' == 'The value of pi is 3.142.' - # Passing an integer after the ':' will cause that field to be a minimum number of characters - # wide. This is useful for making columns line up: + # 在':'后面传递一个整数将使该字段成为最小字符数宽。 这对于使列对齐很有用: table_data = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} table_string = '' for name, phone in table_data.items(): @@ -258,19 +243,17 @@ def test_string_formatting(): 'Jack ==> 4098' 'Dcab ==> 7678') - # The String format() Method + # String format()方法 - # Basic usage of the str.format() method looks like this: + # str.format()方法的基本用法如下: assert 'We are {} who say "{}!"'.format('knights', 'Ni') == 'We are knights who say "Ni!"' - # The brackets and characters within them (called format fields) are replaced with the objects - # passed into the str.format() method. A number in the brackets can be used to refer to the - # position of the object passed into the str.format() method + # 方括号和其中的字符(称为格式字段)被传递到str.format()方法中的对象替换。 + # 括号中的数字可以用来引用传递给str.format()方法的对象的位置 assert '{0} and {1}'.format('spam', 'eggs') == 'spam and eggs' assert '{1} and {0}'.format('spam', 'eggs') == 'eggs and spam' - # If keyword arguments are used in the str.format() method, their values are referred to by - # using the name of the argument. + # 如果关键字参数在str.format()方法中使用,则通过参数的名称引用它们的值。 formatted_string = 'This {food} is {adjective}.'.format( food='spam', adjective='absolutely horrible' @@ -278,7 +261,7 @@ def test_string_formatting(): assert formatted_string == 'This spam is absolutely horrible.' - # Positional and keyword arguments can be arbitrarily combined + # 位置参数和关键字参数可以任意组合 formatted_string = 'The story of {0}, {1}, and {other}.'.format( 'Bill', 'Manfred', @@ -287,16 +270,15 @@ def test_string_formatting(): assert formatted_string == 'The story of Bill, Manfred, and Georg.' - # If you have a really long format string that you don’t want to split up, it would be nice if - # you could reference the variables to be formatted by name instead of by position. This can be - # done by simply passing the dict and using square brackets '[]' to access the keys + # 如果你有一个很长的格式字符串,你不想拆分,如果你可以引用变量的名称,而不是位置。 + # 这可以通过简单地传递字典并使用方括号'[]'来访问键来实现 table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} formatted_string = 'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table) assert formatted_string == 'Jack: 4098; Sjoerd: 4127; Dcab: 8637678' - # This could also be done by passing the table as keyword arguments with the ‘**’ notation. + # 这也可以通过使用“**”作为关键字参数传递表来实现。 formatted_string = 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table) assert formatted_string == 'Jack: 4098; Sjoerd: 4127; Dcab: 8637678' diff --git a/src/data_types/test_tuples.py b/src/data_types/test_tuples.py index b122824e..8805d8a4 100644 --- a/src/data_types/test_tuples.py +++ b/src/data_types/test_tuples.py @@ -1,21 +1,20 @@ -"""Tuples. +""" 元组. @see: https://www.w3schools.com/python/python_tuples.asp @see: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences -A tuple is a collection which is ordered and unchangeable. In Python tuples are written with -round brackets. +元组是有序且不可更改的集合。 在Python中,元组是用圆括弧。 -The Tuples have following properties: -- You cannot change values in a tuple. -- You cannot remove items in a tuple. +元组有以下属性: +- 不能更改元组中的值。 +- 不能删除元组中的项。 """ import pytest def test_tuples(): - """Tuples""" + """ 元组""" fruits_tuple = ("apple", "banana", "cherry") assert isinstance(fruits_tuple, tuple) @@ -23,63 +22,59 @@ def test_tuples(): assert fruits_tuple[1] == "banana" assert fruits_tuple[2] == "cherry" - # You cannot change values in a tuple. + # 不能更改元组中的值。 with pytest.raises(Exception): # pylint: disable=unsupported-assignment-operation fruits_tuple[0] = "pineapple" - # It is also possible to use the tuple() constructor to make a tuple (note the double - # round-brackets). - # The len() function returns the length of the tuple. + # 也可以使用 tuple() 构造函数来创建一个元组 (注意两个圆括号)。 + # len()函数返回元组的长度。 fruits_tuple_via_constructor = tuple(("apple", "banana", "cherry")) assert isinstance(fruits_tuple_via_constructor, tuple) assert len(fruits_tuple_via_constructor) == 3 - # It is also possible to omit brackets when initializing tuples. + # 初始化元组时也可以省略括号。 another_tuple = 12345, 54321, 'hello!' assert another_tuple == (12345, 54321, 'hello!') - # Tuples may be nested: + # 元组可以嵌套: nested_tuple = another_tuple, (1, 2, 3, 4, 5) assert nested_tuple == ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) - # As you see, on output tuples are always enclosed in parentheses, so that nested tuples are - # interpreted correctly; they may be input with or without surrounding parentheses, although - # often parentheses are necessary anyway (if the tuple is part of a larger expression). It is - # not possible to assign to the individual items of a tuple, however it is possible to create - # tuples which contain mutable objects, such as lists. + # 如您所见,在输出时元组总是括在括号中,因此嵌套的元组是正确解读; + # 它们的输入可以带或不带圆括号,尽管圆括号通常是必须的(如果元组是一个更大的表达式的一部分). + # 不能为元组的单个项赋值,但是可以创建包含可变对象的元组,比如列表。 - # A special problem is the construction of tuples containing 0 or 1 items: the syntax has some - # extra quirks to accommodate these. Empty tuples are constructed by an empty pair of - # parentheses; a tuple with one item is constructed by following a value with a comma (it is - # not sufficient to enclose a single value in parentheses). Ugly, but effective. For example: + # 一个特殊的问题是包含0或1项的元组的构造: 语法有一些额外的怪癖来适应这些。 + # 空元组由一对空括号构成; + # 只有一项的元组是通过在值后面加逗号来构造的(将单个值括在圆括号中是不够的). + # 丑,但有效。例如: empty_tuple = () # pylint: disable=len-as-condition assert len(empty_tuple) == 0 # pylint: disable=trailing-comma-tuple - singleton_tuple = 'hello', # <-- note trailing comma + singleton_tuple = 'hello', # <-- 注意后面的逗号 assert len(singleton_tuple) == 1 assert singleton_tuple == ('hello',) - # The following example is called tuple packing: + # 下面的例子被称为元组打包: packed_tuple = 12345, 54321, 'hello!' - # The reverse operation is also possible. + # 反向操作也是可以的。 first_tuple_number, second_tuple_number, third_tuple_string = packed_tuple assert first_tuple_number == 12345 assert second_tuple_number == 54321 assert third_tuple_string == 'hello!' - # This is called, appropriately enough, sequence unpacking and works for any sequence on the - # right-hand side. Sequence unpacking requires that there are as many variables on the left - # side of the equals sign as there are elements in the sequence. Note that multiple assignment - # is really just a combination of tuple packing and sequence unpacking. + # 这被称为序列解包,并适用于右边的任何序列。 + # 序列解包要求等号左边的变量数量与序列中的元素数量相等。 + # 请注意,多重赋值实际上只是元组打包和序列解包的组合。 - # Swapping using tuples. - # Data can be swapped from one variable to another in python using - # tuples. This eliminates the need to use a 'temp' variable. + # 交换使用元组。 + # 数据可以在 python 中使用 + # 元组。这样就不需要使用'temp'变量了。 first_number = 123 second_number = 456 first_number, second_number = second_number, first_number diff --git a/src/data_types/test_type_casting.py b/src/data_types/test_type_casting.py index e5b1fef3..827ef404 100644 --- a/src/data_types/test_type_casting.py +++ b/src/data_types/test_type_casting.py @@ -1,27 +1,22 @@ -"""Type casting. +"""类型转换 @see: https://www.w3schools.com/python/python_casting.asp -There may be times when you want to specify a type on to a variable. This can be done with casting. -Python is an object-orientated language, and as such it uses classes to define data types, -including its primitive types. +有时您可能希望为变量指定类型。这可以通过转换来实现。 +Python是一种面向对象的语言,因此它使用类来定义数据类型, 包括它的基本类型。 -Casting in python is therefore done using constructor functions: +因此 python 中的类型转换是使用构造函数来完成的: -- int() - constructs an integer number from an integer literal, a float literal (by rounding down -to the previous whole number) literal, or a string literal (providing the string represents a -whole number) +- int() - 从一个整数字面值、一个浮点字面值(通过四舍五入)构造一个整数到前一个整数)字面值,或字符串字面值(提供字符串表示整数) -- float() - constructs a float number from an integer literal, a float literal or a string literal -(providing the string represents a float or an integer) +- float() - 从整数字面值、浮点字面值或字符串字面值(提供表示浮点数或整数的字符串)构造浮点数 -- str() - constructs a string from a wide variety of data types, including strings, integer -literals and float literals +- str() - 从各种数据类型构造字符串,包括字符串、整型字面值和浮点字面值 """ def test_type_casting_to_integer(): - """Type casting to integer""" + """类型转换为整数""" assert int(1) == 1 assert int(2.8) == 2 @@ -29,7 +24,7 @@ def test_type_casting_to_integer(): def test_type_casting_to_float(): - """Type casting to float""" + """类型转换为浮点数""" assert float(1) == 1.0 assert float(2.8) == 2.8 @@ -38,7 +33,7 @@ def test_type_casting_to_float(): def test_type_casting_to_string(): - """Type casting to string""" + """类型转换为字符串""" assert str("s1") == 's1' assert str(2) == '2' diff --git a/src/functions/test_function_annotations.py b/src/functions/test_function_annotations.py index 4c6495e6..d02d567b 100644 --- a/src/functions/test_function_annotations.py +++ b/src/functions/test_function_annotations.py @@ -1,27 +1,23 @@ -"""Function Annotations. +"""函数注释。 @see: https://docs.python.org/3/tutorial/controlflow.html#function-annotations -Function annotations are completely optional metadata information about the types used -by user-defined functions. +函数注释是关于用户定义函数使用的类型的完全可选的元数据信息。 -Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no -effect on any other part of the function. Parameter annotations are defined by a colon after the -parameter name, followed by an expression evaluating to the value of the annotation. Return -annotations are defined by a literal ->, followed by an expression, between the parameter list and -the colon denoting the end of the def statement. +注释作为字典存储在函数的__annotations__属性中,对函数的任何其他部分都没有影响。 参数注释通过参数名称后面的冒号定义,后面是求值为注释值的表达式。 +返回注释由文字定义 ->, 后面是一个表达式,在形参表和表示 def 语句结束的冒号之间。 """ def breakfast(ham: str, eggs: str = 'eggs') -> str: """Breakfast creator. - This function has a positional argument, a keyword argument, and the return value annotated. + 这个函数有一个位置参数、一个关键字参数和带注释的返回值。 """ return ham + ' and ' + eggs def test_function_annotations(): - """Function Annotations.""" + """函数注释。""" assert breakfast.__annotations__ == {'eggs': str, 'ham': str, 'return': str} diff --git a/src/functions/test_function_arbitrary_arguments.py b/src/functions/test_function_arbitrary_arguments.py index b3f36627..f2971988 100644 --- a/src/functions/test_function_arbitrary_arguments.py +++ b/src/functions/test_function_arbitrary_arguments.py @@ -1,31 +1,27 @@ -"""Arbitrary Argument Lists +"""任意的参数列表 @see: https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists -Function can be called with an arbitrary number of arguments. These arguments will be wrapped up in -a tuple. Before the variable number of arguments, zero or more normal arguments may occur. +函数可以使用任意数量的参数来调用。这些参数将封装在一个元组中。 +在可变数量的参数之前,可能会出现零个或多个普通参数。 """ def test_function_arbitrary_arguments(): - """Arbitrary Argument Lists""" + """任意的参数列表""" - # When a final formal parameter of the form **name is present, it receives a dictionary - # containing all keyword arguments except for those corresponding to a formal parameter. - # This may be combined with a formal parameter of the form *name which receives a tuple - # containing the positional arguments beyond the formal parameter list. - # (*name must occur before **name.) For example, if we define a function like this: + # 当出现 **name 的最后一个正式形参时,它将接收一个字典,其中包含除与正式形参对应的关键字参数外的所有关键字参数。 + # 这可以与 *name 的形式参数结合使用,该形式参数接收一个包含形式参数列表之外的位置参数的元组。 + # (*name 必须出现在 **name之前。)例如,如果我们这样定义一个函数: def test_function(first_param, *arguments): - """This function accepts its arguments through "arguments" tuple amd keywords dictionary.""" + """这个函数通过“arguments”元组和关键字字典接受它的参数。""" assert first_param == 'first param' assert arguments == ('second param', 'third param') test_function('first param', 'second param', 'third param') - # Normally, these variadic arguments will be last in the list of formal parameters, because - # they scoop up all remaining input arguments that are passed to the function. Any formal - # parameters which occur after the *args parameter are ‘keyword-only’ arguments, meaning that - # they can only be used as keywords rather than positional arguments. + # 通常,这些可变参数将位于形参列表的最后,因为它们将获取传递给函数的所有剩余输入参数。 + # 任何出现在*args形参之后的形式形参都是“仅关键字”参数,这意味着它们只能作为关键字而不是位置参数使用。 def concat(*args, sep='/'): return sep.join(args) diff --git a/src/functions/test_function_decorators.py b/src/functions/test_function_decorators.py index 1603a5ff..05c1c5e9 100644 --- a/src/functions/test_function_decorators.py +++ b/src/functions/test_function_decorators.py @@ -1,43 +1,49 @@ -"""Function Decorators. +"""函数修饰符。 @see: https://www.thecodeship.com/patterns/guide-to-python-function-decorators/ -Function decorators are simply wrappers to existing functions. In the context of design patterns, -decorators dynamically alter the functionality of a function, method or class without having to -directly use subclasses. This is ideal when you need to extend the functionality of functions that -you don't want to modify. We can implement the decorator pattern anywhere, but Python facilitates -the implementation by providing much more expressive features and syntax for that. +函数装饰器只是现有函数的包装器。 +在设计模式的上下文中,装饰器动态地改变函数、方法或类的功能,而不必直接使用子类。 +当您需要扩展不想修改的函数的功能时,这是理想的。 +我们可以在任何地方实现装饰器模式,但 Python 通过提供更具表达性的特性和语法来促进实现。 """ def test_function_decorators(): - """Function Decorators.""" + """函数修饰符。""" - # Function decorators are simply wrappers to existing functions. Putting the ideas mentioned - # above together, we can build a decorator. In this example let's consider a function that - # wraps the string output of another function by p tags. + # 函数装饰器只是现有函数的包装器。把上面提到的想法放在一起,我们就可以建立一个装饰。 + # 在本例中,让我们考虑一个函数,它通过 p 标记包装另一个函数的字符串输出。 - # This is the function that we want to decorate. + # 这就是我们想要装饰的功能。 def greeting(name): return "Hello, {0}!".format(name) - # This function decorates another functions output with
tag. + # 这个函数用
标记修饰了另一个函数的输出。 def decorate_with_p(func): def function_wrapper(name): return "
{0}
".format(func(name)) + return function_wrapper - # Now, let's call our decorator and pass the function we want decorate to it. + # 现在,让我们调用装饰器,并将我们想要装饰的函数传递给它。 my_get_text = decorate_with_p(greeting) - # Here we go, we've just decorated the function output without changing the function itself. + # 开始吧,我们只是修饰了函数的输出,而没有改变函数本身。 + # 执行过程: + # my_get_text('John') + # -> decorate_with_p(greeting('John')) + # -> function_wrapper('John') + # -> "{0}
".format(greeting('John')) + # -> "{0}
".format("Hello, {0}!".format('John')) + # -> 'Hello, John!
' + assert my_get_text('John') == 'Hello, John!
' # With decorator. assert greeting('John') == 'Hello, John!' # Without decorator. - # Now, Python makes creating and using decorators a bit cleaner and nicer for the programmer - # through some syntactic sugar There is a neat shortcut for that, which is to mention the - # name of the decorating function before the function to be decorated. The name of the - # decorator should be prepended with an @ symbol. + # 现在,Python通过一些语法上的“糖果”让程序员创建和使用装饰器变得更干净、更好。 + # 对此,有一个简洁的快捷方式,就是在要装饰的函数之前提到装饰函数的名称。 + # 装饰器的名称应该以@符号作为前缀。 @decorate_with_p def greeting_with_p(name): @@ -45,19 +51,17 @@ def greeting_with_p(name): assert greeting_with_p('John') == 'Hello, John!
' - # Now let's consider we wanted to decorate our greeting function by one more functions to wrap a - # div the string output. + # 现在,让我们考虑一下,我们想要通过多一个函数来装饰我们的greeting函数,以包装字符串输出的div。 - # This will be our second decorator. + # 这是我们的第二个装饰器。 def decorate_with_div(func): def function_wrapper(text): return "Hello, John!