提交 2f35c5ca 编写于 作者: W wizardforcel

2019-10-30 11:17:36

上级 2559deb1
......@@ -17,7 +17,7 @@
+和-可以是加减运算符,也可以是一元符号运算符。 这取决于实际情况。
```
```py
>>> 2
2
>>> +2
......@@ -28,7 +28,7 @@
加号可以用来表示我们有一个正数。 但是它通常不被使用。 减号更改值的符号。
```
```py
>>> a = 1
>>> -a
-1
......@@ -39,7 +39,7 @@
乘法和加法运算符是二进制运算符的示例。 它们与两个操作数一起使用。
```
```py
>>> 3 * 3
9
>>> 3 + 3
......@@ -51,7 +51,7 @@
赋值运算符`=`将值赋给变量。 在数学中,`=`运算符具有不同的含义。 在等式中,`=`运算符是一个相等运算符。 等式的左侧等于右侧。
```
```py
>>> x = 1
>>> x
1
......@@ -60,7 +60,7 @@
在这里,我们为`x`变量分配一个数字。
```
```py
>>> x = x + 1
>>> x
2
......@@ -69,7 +69,7 @@
先前的表达式在数学上没有意义。 但这在编程中是合法的。 该表达式意味着我们向`x`变量加 1。 右边等于 2,并且 2 分配给`x`
```
```py
>>> a = b = c = 4
>>> print(a, b, c)
4 4 4
......@@ -78,7 +78,7 @@
可以为多个变量分配一个值。
```
```py
>>> 3 = y
File "<stdin>", line 1
SyntaxError: can't assign to literal
......@@ -105,7 +105,7 @@ SyntaxError: can't assign to literal
`arithmetic.py`
```
```py
#!/usr/bin/env python
# arithmetic.py
......@@ -128,7 +128,7 @@ print(power)
所有这些都是数学上已知的运算符。
```
```py
$ ./arithmetic.py
33 2 110 4.0
100
......@@ -139,7 +139,7 @@ $ ./arithmetic.py
`division.py`
```
```py
#!/usr/bin/env python
# division.py
......@@ -153,28 +153,28 @@ print(9 % 4)
该示例演示了除法运算符。
```
```py
print(9 / 4)
```
结果为 2.25。 在 Python 2.x 中,/运算符是整数除法运算符。 这在 Python 3 中已更改。在 Python 3 中,/运算符返回一个十进制数。
```
```py
print(9 // 4)
```
//运算符是 Python 3 中的整数运算符。
```
```py
print(9 % 4)
```
`%`运算符称为模运算符。 它找到一个数除以另一个的余数。 `9 % 4`,9 模 4 为 1,因为 4 两次进入 9 且余数为 1。
```
```py
$ ./division.py
3.0
2.25
......@@ -183,7 +183,7 @@ $ ./division.py
```
```
```py
>>> 'return' + 'of' + 'the' + 'king'
'returnoftheking'
......@@ -191,7 +191,7 @@ $ ./division.py
加法运算符还可用于连接字符串。
```
```py
>>> 3 + ' apples'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
......@@ -201,7 +201,7 @@ TypeError: unsupported operand type(s) for +: 'int' and 'str'
我们不能添加整数和字符串。 这导致`TypeError`
```
```py
>>> str(3) + ' apples'
'3 apples'
......@@ -211,7 +211,7 @@ TypeError: unsupported operand type(s) for +: 'int' and 'str'
另一方面,乘法运算符可以与字符串和数字一起使用。
```
```py
>>> 'dollar ' * 5
'dollar dollar dollar dollar dollar '
......@@ -223,7 +223,7 @@ TypeError: unsupported operand type(s) for +: 'int' and 'str'
`andop.py`
```
```py
#!/usr/bin/env python
# andop.py
......@@ -237,7 +237,7 @@ print(False and False)
此示例显示了逻辑和运算符。 仅当两个操作数均为`True`时,逻辑和运算符才对`True`求值。
```
```py
$ ./andop.py
True
False
......@@ -250,7 +250,7 @@ False
`orop.py`
```
```py
#!/usr/bin/env python
# orop.py
......@@ -264,7 +264,7 @@ print(False or False)
如果操作员的一方为`True`,则操作的结果为`True`
```
```py
$ ./orop.py
True
True
......@@ -277,7 +277,7 @@ False
`negation.py`
```
```py
#!/usr/bin/env python
# negation.py
......@@ -290,7 +290,7 @@ print(not ( 4 < 3 ))
该示例显示了 not 运算符的作用。
```
```py
$ ./negation.py
True
False
......@@ -304,7 +304,7 @@ True
`short_circuit.py`
```
```py
#!/usr/bin/env python
# short_circuit.py
......@@ -336,7 +336,7 @@ if (y != 0 and x/y < 100):
上表显示了 Python 关系运算符。
```
```py
>>> 3 < 4
True
>>> 4 == 3
......@@ -350,7 +350,7 @@ True
注意,关系运算符不限于数字。 我们也可以将它们用于其他对象。 尽管它们可能并不总是有意义的。
```
```py
>>> "six" == "six"
True
>>> 'a' < 'b'
......@@ -360,14 +360,14 @@ True
我们也可以比较字符串对象。
```
```py
>>> 'a' < 'b'
```
这里到底发生了什么? 计算机不知道字符或字符串。 对于他们来说,一切都只是数字。 字符是存储在特定表中的特殊数字,例如 ASCII。
```
```py
>>> 'a' > 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
......@@ -379,7 +379,7 @@ TypeError: unorderable types: str() > int()
`compare.py`
```
```py
#!/usr/bin/env python
# compare.py
......@@ -393,7 +393,7 @@ print("b is:", ord('b'))
在内部,a 和 b 字符是数字。 因此,当我们比较两个字符时,我们将比较它们的存储数字。 内置的`ord()`函数返回单个字符的 ASCII 值。
```
```py
$ ./compare.py
True
a is: 97
......@@ -403,7 +403,7 @@ b is: 98
实际上,我们比较两个数字:97 和 98。
```
```py
>>> "ab" > "aa"
True
......@@ -417,7 +417,7 @@ True
`object_identity.py`
```
```py
#!/usr/bin/env python
# object_identity.py
......@@ -436,7 +436,7 @@ print("Python" is "Python")
`==`运算符测试是否相等,而`is`运算符测试对象身份。 我们是否在谈论同一对象。 请注意,更多变量可能引用同一对象。
```
```py
$ ./object_identity.py
True
True
......@@ -457,7 +457,7 @@ True
`membership.py`
```
```py
#!/usr/bin/env python
# membership.py
......@@ -478,21 +478,21 @@ else:
通过成员运算符,我们可以测试元组中是否存在某个项目。
```
```py
if "coin" in items:
```
使用`in`运算符,我们检查`items`元组中是否存在`"coin"`
```
```py
if "bowl" not in items:
```
使用`not in`运算符,我们检查`items`元组中是否不存在`"bowl"`
```
```py
$ ./membership.py
There is a coin in the tuple
There is no bowl in the tuple
......@@ -505,7 +505,7 @@ There is no bowl in the tuple
三元运算符是一个简单的条件分配语句。
```
```py
exp1 if condition else exp2
```
......@@ -514,7 +514,7 @@ exp1 if condition else exp2
`ternary.py`
```
```py
#!/usr/bin/env python
# ternary.py
......@@ -529,14 +529,14 @@ print("Adult: {0}".format(adult))
在许多国家,成年取决于您的年龄。 如果您的年龄超过特定年龄,则您已经成年。 对于三元运算符,这是一种情况。
```
```py
adult = True if age >= 18 else False
```
首先评估条件。 如果年龄大于或等于 18,则返回`True`。 如果不是,则返回`else`关键字后面的值。 然后,将返回的值分配给`adult`变量。
```
```py
$ ./ternary.py
Adult: True
......@@ -559,7 +559,7 @@ Adult: True
按位取反运算符分别将 1 更改为 0,将 0 更改为 1。
```
```py
>>> ~7
-8
>>> ~-8
......@@ -571,7 +571,7 @@ Adult: True
按位,运算符在两个数字之间进行逐位比较。 仅当操作数中的两个对应位均为 1 时,位位置的结果才为 1。
```
```py
00110
& 00011
= 00010
......@@ -580,7 +580,7 @@ Adult: True
第一个数字是二进制表示法 6,第二个数字是 3,最终结果是 2。
```
```py
>>> 6 & 3
2
>>> 3 & 6
......@@ -590,7 +590,7 @@ Adult: True
按位或运算符在两个数字之间进行逐位比较。 如果操作数中的任何对应位为 1,则位位置的结果为 1。
```
```py
00110
| 00011
= 00111
......@@ -599,7 +599,7 @@ Adult: True
结果为`00110`或十进制 7。
```
```py
>>> 6 | 3
7
......@@ -607,7 +607,7 @@ Adult: True
按位互斥或运算符在两个数字之间进行逐位比较。 如果操作数中对应位中的一个或另一个(但不是全部)为 1,则位位置的结果为 1。
```
```py
00110
^ 00011
= 00101
......@@ -616,7 +616,7 @@ Adult: True
结果为`00101`或十进制 5。
```
```py
>>> 6 ^ 3
5
......@@ -628,7 +628,7 @@ Adult: True
`bitwise_or.py`
```
```py
#!/usr/bin/env python
# bitwise_or.py
......@@ -648,7 +648,7 @@ app.MainLoop()
最后,我们还有按位移位运算符。 按位移位运算符向右或向左移位。
```
```py
number << n : multiply number 2 to the nth power
number >> n : divide number by 2 to the nth power
......@@ -656,7 +656,7 @@ number >> n : divide number by 2 to the nth power
这些运算符也称为算术移位。
```
```py
00110
>> 00001
= 00011
......@@ -665,13 +665,13 @@ number >> n : divide number by 2 to the nth power
我们将数字 6 的每个位向右移动。 等于将 6 除以 2。结果为`00011`或十进制 3。
```
```py
>>> 6 >> 1
3
```
```
```py
00110
<< 00001
= 01100
......@@ -680,7 +680,7 @@ number >> n : divide number by 2 to the nth power
我们将数字 6 的每个位向左移动。 等于将数字 6 乘以 2。结果为`01100`或十进制 12。
```
```py
>>> 6 << 1
12
......@@ -690,7 +690,7 @@ number >> n : divide number by 2 to the nth power
复合赋值运算符由两个运算符组成。 他们是速记员。
```
```py
>>> i = 1
>>> i = i + 1
>>> i
......@@ -705,7 +705,7 @@ number >> n : divide number by 2 to the nth power
其他复合运算符是:
```
```py
-= *= /= //= %= **= &= |= ^= >>= <<=
```
......@@ -716,14 +716,14 @@ number >> n : divide number by 2 to the nth power
以下表达式 28 或 40 的结果是什么?
```
```py
3 + 5 * 5
```
像数学中一样,乘法运算符的优先级高于加法运算符。 结果是 28。
```
```py
(3 + 5) * 5
```
......@@ -732,7 +732,7 @@ number >> n : divide number by 2 to the nth power
以下列表显示了 Python 中的运算符优先级。
```
```py
unary + - ~
**
* / %
......@@ -752,7 +752,7 @@ or
`precedence.py`
```
```py
#!/usr/bin/env python
# precedence.py
......@@ -768,21 +768,21 @@ print(not (True or True))
在此代码示例中,我们显示一些常见的表达式。 每个表达式的结果取决于优先级。
```
```py
print(2 ** 3 * 5)
```
幂运算符的优先级高于乘法运算符。 首先,对`2 ** 3`求值,返回 8。然后将结果乘以 5,结果为 40。
```
```py
print(not True or True)
```
在这种情况下,`not`运算符具有更高的优先级。 首先,将第一个`True`值取反为`False`,然后`or`运算符组合`False``True`,最后得到`True`
```
```py
$ ./precedence.py
28
40
......@@ -796,7 +796,7 @@ False
`positive.py`
```
```py
#!/usr/bin/env python
# positive.py
......@@ -811,7 +811,7 @@ if (a > 0 and b > 0):
`and`运算符等待两个布尔值。 如果其中一个操作数不是布尔值,则会出现语法错误。 在 Python 中,关系运算符在逻辑与之前进行求值。
```
```py
$ ./positive.py
a and b are positive integers
......@@ -821,7 +821,7 @@ a and b are positive integers
有时,优先级不能令人满意地确定表达式的结果。 还有另一个规则称为关联性。 运算符的关联性确定优先级与相同的运算符的评估顺序。
```
```py
9 / 3 * 3
```
......@@ -832,7 +832,7 @@ a and b are positive integers
另一方面,赋值运算符是正确关联的。
```
```py
>>> a = b = c = d = 0
>>> a, b, c, d
(0, 0, 0, 0)
......@@ -843,7 +843,7 @@ a and b are positive integers
复合赋值运算符从右到左关联。
```
```py
>>> j = 0
>>> j *= 3 + 1
>>> j
......
......@@ -12,7 +12,7 @@ Python 关键字是构成 Python 语言词汇的特殊单词。 它是保留字
以下是 Python 编程语言的关键字列表。
```
```py
False def if raise
None del import return
True elif in try
......@@ -29,7 +29,7 @@ Python 是一种动态语言。 它随时间变化。 关键字列表将来可
`keywords.py`
```
```py
#!/usr/bin/env python
# keywords.py
......@@ -44,7 +44,7 @@ print("Python keywords: ", keyword.kwlist)
该脚本打印 Python 的版本及其实际的关键字列表。
```
```py
$ ./keywords.py
Python version: sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
Python keywords: ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
......@@ -62,7 +62,7 @@ Python keywords: ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'cla
`while_kwd.py`
```
```py
#!/usr/bin/env python
# while_kwd.py
......@@ -83,7 +83,7 @@ print("The sum is:", mysum)
在我们的脚本中,我们要计算数字列表中所有值的总和。 我们利用`while`循环。 我们确定列表的长度。 反复执行`while`循环,直到`i`等于零为止。 在循环的主体中,我们递减计数器并计算值的总和。
```
```py
$ ./while_kwd.py
The sum is: 104
......@@ -95,7 +95,7 @@ The sum is: 104
`break_kwd.py`
```
```py
#!/usr/bin/env python
# break_kwd.py
......@@ -116,7 +116,7 @@ print()
在我们的示例中,我们打印随机整数。 如果数字等于 22,则用`break`关键字中断循环。
```
```py
$ ./break_kwd.py
14 14 30 16 16 20 23 15 17 22
......@@ -126,7 +126,7 @@ $ ./break_kwd.py
`continue_kwd.py`
```
```py
#!/usr/bin/env python
# continue_kwd.py
......@@ -150,7 +150,7 @@ while num < 1000:
`if_kwd.py`
```
```py
#!/usr/bin/env python
# if_kwd.py
......@@ -172,7 +172,7 @@ else:
`elif_kwd.py`
```
```py
#!/usr/bin/env python
# elif_kwd.py
......@@ -195,7 +195,7 @@ else:
如果第一个测试的评估结果为`False`,那么我们继续下一个测试。 如果没有一个测试是`True`,则执行 else 语句。
```
```py
$ ./elif_kwd.py
Hello Luke!
......@@ -207,7 +207,7 @@ Hello Luke!
`for_kwd.py`
```
```py
#!/usr/bin/env python
# for_kwd.py
......@@ -227,7 +227,7 @@ for i in lyrics:
在该示例中,我们有一个`lyrics`变量,该变量具有歌曲的节奏。 我们遍历文本并逐个字符打印文本。 `print`语句中的逗号阻止将每个字符打印在新行上。
```
```py
$ ./for_kwd.py
A r e y o u r e a l l y h e r e o r a m I d r e a m i n g
I c a n ' t t e l l d r e a m s f r o m t r u t h
......@@ -244,7 +244,7 @@ I c a n h a r d l y r e m e m b e r y o u r f a c e a n y m o r e
`objects.py`
```
```py
#!/usr/bin/env python
# objects.py
......@@ -263,7 +263,7 @@ print("Python" is "Python")
`==`运算符测试是否相等。 `is`关键字测试对象身份。 我们是否在谈论同一对象。 请注意,多个变量可能引用同一对象。
```
```py
$ ./objects.py
True
True
......@@ -280,7 +280,7 @@ True
`not_kwd.py`
```
```py
#!/usr/bin/env python
# not_kwd.py
......@@ -296,7 +296,7 @@ if grade not in grades:
在我们的示例中,我们测试了等级值是否来自可能等级的列表。
```
```py
$ ./not_kwd.py
unknown grade
......@@ -306,7 +306,7 @@ unknown grade
`and_kwd.py`
```
```py
#!/usr/bin/env python
# and_kwd.py
......@@ -321,7 +321,7 @@ if age < 55 and sex == "M":
在我们的示例中,我们测试是否满足两个条件。 如果变量`age`小于`55`且变量`sex`等于`"M"`,则将`"a young male"`字符串打印到控制台。
```
```py
$ ./and_kwd.py
a young male
......@@ -331,7 +331,7 @@ a young male
`or_kwd.py`
```
```py
#!/usr/bin/env python
# or_kwd.py
......@@ -352,7 +352,7 @@ if (name == "Robert" or name == "Frank" or name == "Jack"
`short_circuit.py`
```
```py
#!/usr/bin/env python
# short_circuit.py
......@@ -375,7 +375,7 @@ if (y != 0 and x/y < 100):
`import_kwd.py`
```
```py
#!/usr/bin/env python
# import_kwd.py
......@@ -392,7 +392,7 @@ print(math.pi)
`as_kwd.py`
```
```py
#!/usr/bin/env python
# as_kwd.py
......@@ -408,7 +408,7 @@ print()
在这种情况下,我们将导入随机模块。 我们打印十个随机整数。 我们给随机模块一个不同的别名,即`rnd`。 在脚本中,我们使用新别名引用模块。
```
```py
$ ./as_kwd.py
1 2 5 10 10 8 2 9 7 2
......@@ -418,7 +418,7 @@ $ ./as_kwd.py
`from_kwd.py`
```
```py
#!/usr/bin/env python
# from_kwd.py
......@@ -431,7 +431,7 @@ print(version)
`sys`模块中,导入`version`变量。 如果要打印,则不需要使用模块名称。 版本变量被直接导入到我们的命名空间中,我们可以直接引用它。
```
```py
$ ./from_kwd.py
3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
......@@ -443,7 +443,7 @@ $ ./from_kwd.py
`def_kwd.py`
```
```py
#!/usr/bin/env python
# def_kwd.py
......@@ -465,7 +465,7 @@ print(a, b)
`lambda_kwd.py`
```
```py
#!/usr/bin/env python
# lambda_kwd.py
......@@ -482,7 +482,7 @@ print()
如您在前面的示例中看到的,我们没有使用`def`关键字创建新函数。 取而代之的是,我们动态使用内联函数。
```
```py
$ ./lambda_kwd.py
1 4 9 16 25
......@@ -492,7 +492,7 @@ $ ./lambda_kwd.py
`global_kwd.py`
```
```py
#!/usr/bin/env python
# global_kwd.py
......@@ -511,7 +511,7 @@ print(x)
通常,在函数内部分配`x`变量时,我们会创建一个新的局部变量,该局部变量仅在该函数中有效。 但是,如果使用 global 关键字,则会在函数定义中更改变量 ouside。
```
```py
$ ./global_kwd.py
45
......@@ -521,7 +521,7 @@ $ ./global_kwd.py
接下来,我们将使用与异常处理一起使用的关键字。
```
```py
$ cat films
Fargo
Aguirre, der Zorn Gottes
......@@ -535,7 +535,7 @@ Notes on a scandal
`try_except_finally.py`
```
```py
#!/usr/bin/env python
# try_except_finally.py
......@@ -567,7 +567,7 @@ finally:
`raise_kwd.py`
```
```py
#!/usr/bin/env python
# raise_kwd.py
......@@ -590,7 +590,7 @@ else:
在该示例中,我们仅期望是/否值。 对于其他可能性,我们提出一个例外。
```
```py
$ ./raise_kwd.py
This is not a yes or no answer
Traceback (most recent call last):
......@@ -606,7 +606,7 @@ __main__.YesNoException
`del_kwd.py`
```
```py
#!/usr/bin/env python
# del_kwd.py
......@@ -621,7 +621,7 @@ print(a)
在我们的示例中,我们有四个整数的列表。 我们从列表中删除第一个数字。 结果将打印到控制台。
```
```py
$ ./del_kwd.py
[1, 2, 3, 4]
[3, 4]
......@@ -632,7 +632,7 @@ $ ./del_kwd.py
`pass`关键字不执行任何操作。 在某些情况下,这是一个非常方便的关键字。
```
```py
def function():
pass
......@@ -644,7 +644,7 @@ def function():
`assert_kwd.py`
```
```py
#!/usr/bin/env python
# assert_kwd.py
......@@ -658,7 +658,7 @@ assert salary > 0
在程序执行期间,犯了一个错误。 薪水变成负数。
```
```py
$ ./assert_kwd.py
Traceback (most recent call last):
File "./assert_kwd.py", line 8, in <module>
......@@ -673,7 +673,7 @@ AssertionError
`class_kwd.py`
```
```py
#!/usr/bin/env python
# class_kwd.py
......@@ -697,7 +697,7 @@ sq.area()
`exec_kwd.py`
```
```py
#!/usr/bin/env python
# exec_kwd.py
......@@ -708,7 +708,7 @@ exec("for i in [1, 2, 3, 4, 5]: print(i, end=' ')")
我们使用 for 循环从列表中打印五个数字; 全部都在`exec`关键字内。
```
```py
$ ./exec_kwd.py
1 2 3 4 5
......@@ -720,7 +720,7 @@ $ ./exec_kwd.py
`in_kwd.py`
```
```py
#!/usr/bin/env python
# in_kwd.py
......@@ -736,7 +736,7 @@ print()
在此示例中,in 关键字测试数字 4 是否在元组中。 第二种用法是在 for 循环中遍历元组。 内置函数`range()`返回整数 0 .. 24。
```
```py
$ ./in_kwd.py
False
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
......@@ -747,7 +747,7 @@ False
`yield_kwd.py`
```
```py
#!/usr/bin/env python
# yield_kwd.py
......@@ -765,7 +765,7 @@ print(it.__next__())
`yield`关键字退出生成器并返回一个值。
```
```py
$ ./yield_kwd.py
11
......
......@@ -24,7 +24,7 @@ Python 中的函数是一等公民。 这意味着函数与 Python 中的其他
使用`def`关键字创建一个函数。 函数块中的语句必须缩进。
```
```py
def function():
pass
......@@ -34,7 +34,7 @@ def function():
该函数稍后在需要时执行。 我们说我们调用函数。 如果我们调用一个函数,则会执行函数体内的语句。 在调用函数之前,它们不会执行。
```
```py
myfunc()
```
......@@ -43,7 +43,7 @@ myfunc()
`ret.py`
```
```py
#!/usr/bin/env python
"""
......@@ -72,7 +72,7 @@ print(a, b)
我们定义两个函数。 第一个函数打印模块文档字符串。 第二个返回模块的路径。 函数可能会或可能不会返回值。 如果函数没有返回值,则它隐式返回`None``__doc__``__file__`是特殊的状态属性。 请注意,属性的两侧都有两个下划线。
```
```py
$ ./ret.py
The ret.py script shows how to work with
......@@ -90,7 +90,7 @@ None C:/Users/Jano/PycharmProjects/Simple/simple.py
`func_prec.py`
```
```py
#!/usr/bin/env python
# func_prec.py
......@@ -108,7 +108,7 @@ def f2():
在上面的示例中,我们有两个函数定义。 一行被注释。 函数调用不能超出其定义。
```
```py
#f2()
def f2():
......@@ -124,7 +124,7 @@ def f2():
`defining.py`
```
```py
#!/usr/bin/env python
# defining.py
......@@ -151,7 +151,7 @@ g()
在此示例中,我们在三个不同的位置定义了`f()`函数。
```
```py
# defining.py
class Some():
......@@ -164,7 +164,7 @@ class Some():
静态方法在`Some`类中用装饰器定义。
```
```py
def f():
print("f() function")
......@@ -172,7 +172,7 @@ def f():
该函数在模块中定义。
```
```py
def g():
def f():
print("f() inner function")
......@@ -182,7 +182,7 @@ def g():
此处,`f()`函数在另一个`g()`函数内部定义。 这是一个内部函数。
```
```py
Some.f()
f()
g()
......@@ -191,7 +191,7 @@ g()
通过使用方括号指定类名称,点运算符和函数名称来调用静态方法。 其他函数使用其名称和方括号来调用。
```
```py
$ ./defining.py
f() method
f() function
......@@ -207,7 +207,7 @@ Python 中的函数是对象。 它们可以像 Python 中的其他对象一样
`fun_obj.py`
```
```py
#!/usr/bin/env python
# fun_obj.py
......@@ -227,7 +227,7 @@ print(f.__name__)
在此脚本中,我们表明我们的函数也是一个对象。
```
```py
def f():
"""This function prints a message """
......@@ -237,21 +237,21 @@ def f():
我们定义一个`f()`函数。 它将消息打印到控制台。 它还具有一个文档字符串。
```
```py
print(isinstance(f, object))
```
`isinstance()`函数检查`f()`函数是否是`object`的实例。 Python 中的所有对象均从该基本实体继承。
```
```py
print(id(f))
```
Python 中的每个对象都有一个唯一的 ID。 `id()`函数返回对象的 ID。
```
```py
print(f.__doc__)
print(f.__name__)
......@@ -259,7 +259,7 @@ print(f.__name__)
对象可能具有属性; 我们打印函数的两个属性:`__doc__``__name__`
```
```py
$ ./fun_obj.py
True
140353774014536
......@@ -274,7 +274,7 @@ f
`fun_coll.py`
```
```py
#!/usr/bin/env python
# fun_coll.py
......@@ -300,7 +300,7 @@ h(g)
我们定义了三个函数。 我们将它们放在一个元组中,然后将它们传递给函数。
```
```py
a = (f, g, h)
for i in a:
......@@ -310,7 +310,7 @@ for i in a:
我们将三个函数对象放在一个元组中,并使用 for 循环遍历它。
```
```py
h(f)
h(g)
......@@ -318,7 +318,7 @@ h(g)
我们将`f()``g()`函数传递给`h()`函数。
```
```py
$ ./fun_coll.py
<function f at 0x0000015B998E9D08>
<function g at 0x0000015B998E9E18>
......@@ -336,7 +336,7 @@ $ ./fun_coll.py
`three_kinds.py`
```
```py
#!/usr/bin/env python
from math import sqrt
......@@ -352,14 +352,14 @@ print(sqrt(81))
上面的代码中存在三种函数。
```
```py
from math import sqrt
```
`sqrt()`函数是从数学模块导入的。
```
```py
def cube(x):
return x * x * x
......@@ -367,7 +367,7 @@ def cube(x):
cube()函数是一个自定义函数。
```
```py
print(abs(-1))
```
......@@ -380,7 +380,7 @@ print(abs(-1))
`returning.py`
```
```py
#!/usr/bin/env python
# returning.py
......@@ -401,7 +401,7 @@ print(show_message("Ready."))
我们定义了两个函数。 一个使用`return`关键字,另一个则不使用。
```
```py
def show_message(msg):
print(msg)
......@@ -409,7 +409,7 @@ def show_message(msg):
`show_message()`函数不会显式返回值。 它在控制台上显示一条消息。
```
```py
def cube(x):
return x * x * x
......@@ -417,28 +417,28 @@ def cube(x):
`cube()`函数计算一个表达式,并使用`return`关键字返回其结果。
```
```py
x = cube(3)
```
在这一行中,我们称为`cube()`函数。 返回`cube()`函数的计算结果,并将其分配给`x`变量。 现在保存结果值。
```
```py
show_message("Computation finished.")
```
我们以消息为参数调用`show_message()`函数。 该消息将打印到控制台。 我们不期望此函数有值。
```
```py
print(show_message("Ready."))
```
此代码产生两行。 一种是通过`show_message()`函数打印的消息。 另一个是`None`值,该值由没有`return`语句的函数隐式发送。
```
```py
$ ./returning.py
27
Computation finished.
......@@ -453,7 +453,7 @@ None
`returning2.py`
```
```py
#!/usr/bin/env python
# returning2.py
......@@ -478,21 +478,21 @@ print(mx, mn, ln, sm)
`stats()`函数的定义。 此函数返回四个值。
```
```py
return _mx, _mn, _ln, _sm
```
`return`关键字发回四个数字。 这些数字用逗号分隔。 实际上,我们已经发送了包含这四个值的元组。 我们也可以返回列表而不是元组。
```
```py
mx, mn, ln, sm = stats(n)
```
返回的值分配给局部变量。
```
```py
$ ./returning2.py
(5, 1, 5, 15)
5 1 5 15
......@@ -507,7 +507,7 @@ Python 本质上是动态的。 可以重新定义已经定义的函数。
`redefinition.py`
```
```py
#!/usr/bin/env python
# redefinition.py
......@@ -529,14 +529,14 @@ show_message("Processing.")
我们定义一个`show_message()`函数。 稍后,我们提供相同函数的新定义。
```
```py
from time import gmtime, strftime
```
从时间模块中,我们导入两个函数,用于计算当前时间。
```
```py
def show_message(msg):
print(msg)
......@@ -544,7 +544,7 @@ def show_message(msg):
这是函数的第一个定义。 它仅将消息打印到控制台。
```
```py
def show_message(msg):
print(strftime("%H:%M:%S", gmtime()))
print(msg)
......@@ -553,7 +553,7 @@ def show_message(msg):
在源代码的后面,我们设置了`showMessage()`函数的新定义。 该消息之前带有时间戳。
```
```py
$ ./redefinition.py
Ready.
23:49:33 Processing.
......@@ -568,7 +568,7 @@ Ready.
`fahrenheit.py`
```
```py
#!/usr/bin/env python
# fahrenheit.py
......@@ -584,7 +584,7 @@ print(C2F(30))
在我们的示例中,我们将摄氏温度转换为华氏温度。 `C2F()`函数接受一个参数 c,即摄氏温度。
```
```py
$ ./fahrenheit.py
212
32
......@@ -596,7 +596,7 @@ Python 函数中的参数可能具有隐式值。 如果未提供任何值,则
`fun_implicit.py`
```
```py
#!/usr/bin/env python
# fun_implicit.py
......@@ -618,7 +618,7 @@ print(power(5, 5))
在这里,我们创建了幂函数。 该函数有一个带有隐式值的参数。 我们可以使用一个或两个参数来调用该函数。
```
```py
$ ./fun_implicit.py
9
27
......@@ -630,7 +630,7 @@ Python 函数可以使用关键字指定其参数。 这意味着在调用函数
`fun_keywords.py`
```
```py
#!/usr/bin/env python
# fun_keywords.py
......@@ -648,7 +648,7 @@ display("Joan", 24, "F")
在此示例中,我们指定参数的顺序很重要。 否则,我们将得到错误的结果。
```
```py
$ ./fun_keywords.py
Name: Lary
Age: 43
......@@ -661,7 +661,7 @@ Sex: F
`fun_keywords2.py`
```
```py
#!/usr/bin/env python
# fun_keywords2.py
......@@ -679,14 +679,14 @@ display(name="Joan", age=24, sex="F")
现在我们用它们的关键字来调用函数。 可以更改顺序,尽管不建议这样做。 请注意,我们不能在关键字参数之后使用非关键字参数。 这将导致语法错误。
```
```py
display("Joan", sex="F", age=24)
```
这是法律构想。 非关键字参数后可以跟关键字参数。
```
```py
display(age=24, name="Joan", "F")
```
......@@ -697,7 +697,7 @@ Python 中的函数可以接受任意数量的参数。
`arbitrary_args.py`
```
```py
#!/usr/bin/env python
# arbitrary_args.py
......@@ -721,7 +721,7 @@ print(do_sum(1, 2, 3, 4, 5))
我们使用`*`运算符表示该函数接受任意数量的参数。 `do_sum()`函数返回所有参数的总和。 函数主体中的第一个字符串称为函数文档字符串。 用于记录函数。 该字符串必须用三引号引起来。
```
```py
$ ./arbitrary_args.py
Function returns the sum
of all values
......@@ -734,7 +734,7 @@ of all values
`details.py`
```
```py
#!/usr/bin/env python
# details.py
......@@ -750,7 +750,7 @@ display(name="Larry", age=43, sex="M")
本示例说明了这种情况。 我们可以提供任意数量的键值参数。 该函数将处理所有这些。
```
```py
$ ./details.py
age: 43
name: Larry
......@@ -764,7 +764,7 @@ sex: M
`passing_by_reference.py`
```
```py
#!/usr/bin/env python
# passing_by_reference.py
......@@ -788,7 +788,7 @@ print("After function call:", n)
在我们的示例中,我们将整数列表传递给函数。 该对象在函数体内被修改。 调用该函数(原始对象)后,将修改整数列表。
```
```py
def f(x):
x.pop()
......@@ -800,7 +800,7 @@ def f(x):
在函数主体中,我们使用原始对象。 不带对象的副本。 在许多编程语言中,默认情况下,我们将收到对象的副本。
```
```py
$ ./passing_by_reference.py
Original list: [1, 2, 3, 4, 5]
Inside f(): [0, 1, 2, 3]
......@@ -816,7 +816,7 @@ After function call: [0, 1, 2, 3]
`local_variable.py`
```
```py
#!/usr/bin/env python
# local_variable.py
......@@ -834,7 +834,7 @@ f()
在函数体中定义的变量具有局部范围。 它仅在函数体内有效。
```
```py
$ ./local_variable.py
Outside function Jack
Within function Robert
......@@ -845,7 +845,7 @@ Within function Robert
`global_variable.py`
```
```py
#!/usr/bin/env python
# global_variable.py
......@@ -862,7 +862,7 @@ f()
默认情况下,我们可以在函数体内获取全局变量的内容。
```
```py
$ ./global_variable.py
Outside function Jack
Within function Jack
......@@ -873,7 +873,7 @@ Within function Jack
`global_variable2.py`
```
```py
#!/usr/bin/env python
# global_variable2.py
......@@ -894,7 +894,7 @@ print("Outside function", name)
现在,我们将在函数内部更改全局名称变量的内容。
```
```py
global name
name = "Robert"
......@@ -902,7 +902,7 @@ name = "Robert"
使用`global`关键字,我们引用在函数主体外部定义的变量。 该变量被赋予一个新值。
```
```py
$ ./global_variable2.py
Outside function Jack
Within function Robert
......@@ -918,7 +918,7 @@ Lambda 函数仅限于单个表达式。 它们可以在可以使用常规函数
`lambda_fun.py`
```
```py
#!/usr/bin/env python
# lambda_fun.py
......@@ -932,21 +932,21 @@ print(z(8))
这是 lambda 函数的一个小例子。
```
```py
z = lambda x: x * y
```
`lambda`关键字创建一个匿名函数。 `x`是传递给 lambda 函数的参数。 参数后跟一个冒号。 冒号旁边的代码是在调用 lambda 函数时执行的表达式。 lambda 函数被分配给`z`变量。
```
```py
print(z(8))
```
lambda 函数被执行。 数字 8 传递给匿名函数,结果返回 48。 请注意,`z`不是此函数的名称。 它只是分配了匿名函数的变量。
```
```py
$ ./lambda_fun.py
48
......@@ -958,7 +958,7 @@ lambda 函数可以与`map()`或`filter()`函数之类的 Python 语言的其他
`lambda_fun2.py`
```
```py
#!/usr/bin/env python
# lambda_fun2.py
......@@ -972,14 +972,14 @@ print(list(ft))
在示例中,我们列出了摄氏温度。 我们创建一个包含华氏温度的新列表。
```
```py
ft = map(lambda t: (9.0/5)*t + 32, cs)
```
`map()`函数将匿名函数应用于`cs`列表的每个元素。 它返回计算出的华氏温度的可迭代值。
```
```py
$ ./lambda_fun2.py
[14.0, 32.0, 59.0, 86.0, 104.0]
......
......@@ -10,7 +10,7 @@ Python 中的所有内容都是一个对象。 UNIX 中的所有内容都是文
`open()`函数用于在 Python 中打开文件。
```
```py
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None)
```
......@@ -32,7 +32,7 @@ open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None)
`works.txt`
```
```py
Lost Illusions
Beatrix
Honorine
......@@ -49,7 +49,7 @@ Cousin Bette
`read_width.py`
```
```py
#!/usr/bin/env python
# read_width.py
......@@ -63,14 +63,14 @@ with open('works.txt', 'r') as f:
该示例读取`works.txt`文件的内容。
```
```py
with open('works.txt', 'r') as f:
```
通过`open()`函数,我们打开`works.txt`文件进行读取。 文件对象的别名为`f``with`语句负责处理异常和关闭打开的文件。
```
```py
contents = f.read()
```
......@@ -83,7 +83,7 @@ contents = f.read()
`read_data.py`
```
```py
#!/usr/bin/env python
# read_data.py
......@@ -99,7 +99,7 @@ with open('works.txt', 'r') as f:
该代码示例从文件中读取了五个字母,并将它们打印到控制台。 然后读取并打印另外九个字母。 第二个操作继续从第一个操作结束的位置读取。
```
```py
$ ./read_data.py
Lost
Illusions
......@@ -114,7 +114,7 @@ Illusions
`file_positions.py`
```
```py
#!/usr/bin/env python
# file_positions.py
......@@ -132,7 +132,7 @@ with open('works.txt', 'r') as f:
在示例中,我们读取 14 个字节,然后确定并打印当前文件位置。 我们将当前文件位置移到`seek()`的开头,再读取 30 个字节。
```
```py
$ ./file_positions.py
Lost Illusions
The current file position is 14
......@@ -150,7 +150,7 @@ Honorin
`readbyline.py`
```
```py
#!/usr/bin/env python
# readbyline.py
......@@ -171,21 +171,21 @@ with open('works.txt', 'r') as f:
使用`readline()`方法和 while 循环,我们从文件中读取了所有行。
```
```py
while True:
```
我们开始无止境的循环; 因此,我们稍后必须使用`break`语句跳过循环。
```
```py
line = f.readline()
```
从文件中读取一行。
```
```py
if not line:
break
......@@ -200,7 +200,7 @@ else:
`read_file.py`
```
```py
#!/usr/bin/env python
# read_file.py
......@@ -221,7 +221,7 @@ with open('works.txt', 'r') as f:
`readlines.py`
```
```py
#!/usr/bin/env python
# readlines.py
......@@ -244,7 +244,7 @@ with open('works.txt', 'r') as f:
`strophe.py`
```
```py
#!/usr/bin/env python
# strophe.py
......@@ -262,7 +262,7 @@ with open('strophe.txt', 'w') as f:
这次我们以“ w”模式打开文件,以便我们可以对其进行写入。 如果该文件不存在,则会创建它。 如果存在,它将被覆盖。
```
```py
$ cat strophe.txt
Incompatible, it don't matter though
'cos someone's bound to hear my cry
......@@ -291,7 +291,7 @@ Python 中的标准输入和输出是`sys`模块中的对象。
`read_name.py`
```
```py
#!/usr/bin/env python
# read_name.py
......@@ -319,7 +319,7 @@ print('Your name is:', name)
`read()`方法从标准输入读取一个字符。 在我们的示例中,系统提示您输入“输入您的姓名”。 我们输入名称,然后按`输入``输入`键生成`new line`字符:`\n`
```
```py
$ ./read_name.py
Enter your name: Peter
Your name is: Peter
......@@ -332,7 +332,7 @@ Your name is: Peter
`input_example.py`
```
```py
#!/usr/bin/env python
# input_example.py
......@@ -343,7 +343,7 @@ print('You have entered:', data)
```
```
```py
$ ./input_example.py
Enter value: Hello there
You have entered: Hello there
......@@ -356,7 +356,7 @@ You have entered: Hello there
`std_output.py`
```
```py
#!/usr/bin/env python
# std_output.py
......@@ -370,7 +370,7 @@ sys.stdout.write('Honore de Balzac, Lost Illusions\n')
在示例中,我们将一些文本写入标准输出。 在我们的例子中,这是终端控制台。 我们使用`write()`方法。
```
```py
$ ./stdout.py
Honore de Balzac, Father Goriot
Honore de Balzac, Lost Illusions
......@@ -381,7 +381,7 @@ Honore de Balzac, Lost Illusions
`print_fun.py`
```
```py
#!/usr/bin/env python
# print_fun.py
......@@ -400,7 +400,7 @@ print()
在此示例中,我们使用`sep``end`参数。 `sep`分隔打印的对象,`end`定义最后打印的内容。
```
```py
$ ./print_fun.py
Honore de Balzac
The Splendors and Miseries of Courtesans:Gobseck:Father Goriot
......@@ -414,7 +414,7 @@ The Splendors and Miseries of Courtesans:Gobseck:Father Goriot
`print2file.py`
```
```py
#!/usr/bin/env python
# print2file.py
......@@ -429,7 +429,7 @@ with open('works.txt', 'w') as f:
我们打开一个文件,并在其中写入 Balzac 书的三个书名。 文件对象被赋予`file`参数。
```
```py
$ cat works.txt
Beatrix
Honorine
......@@ -443,7 +443,7 @@ The firm of Nucingen
`redirect.py`
```
```py
#!/usr/bin/env python
# redirect.py
......@@ -467,7 +467,7 @@ with open('output.txt', 'w') as f:
`redirect.py`脚本中,我们将标准输出重定向到常规文件`output.txt`。 然后,我们恢复原始的标准输出。 `std.output`的原始值保存在特殊的`sys.__stdout__`变量中。
```
```py
$ ./redirect.py
Bianchon
Lambert
......@@ -485,7 +485,7 @@ Collin
`pickle_ex.py`
```
```py
#!/usr/bin/env python
# pickle_ex.py
......@@ -521,7 +521,7 @@ print(monica.get_age())
在我们的脚本中,我们定义一个`Person`类。 我们创建一个人。 我们使用`dump()`方法腌制对象。 我们关闭文件,再次打开以进行读取,然后使用`load()`方法解开对象。
```
```py
$ ./pickle_ex.py
Monica
15
......
......@@ -25,7 +25,7 @@ Python 中的所有内容都是一个对象。 对象是 Python OOP 程序的基
`object_types.py`
```
```py
#!/usr/bin/env python
# object_types.py
......@@ -48,7 +48,7 @@ print(type(sys))
在此示例中,我们显示所有这些实体实际上都是对象。 `type()`函数返回指定对象的类型。
```
```py
$ ./object_types.py
<class 'int'>
<class 'str'>
......@@ -69,7 +69,7 @@ $ ./object_types.py
`first_object.py`
```
```py
#!/usr/bin/env python
# first_object.py
......@@ -86,7 +86,7 @@ print(type(First))
这是我们的头等舱。 该类的主体暂时留空。 按照惯例,给类起一个以大写字母开头的名称。
```
```py
class First:
pass
......@@ -94,14 +94,14 @@ class First:
在这里,我们定义`First`类。 请注意,默认情况下,所有类均从基`object`继承。
```
```py
fr = First()
```
在这里,我们创建`First`类的新实例。 换句话说,我们实例化了`First`类。 `fr`是对我们新对象的引用。
```
```py
$ ./first_object.py
<class '__main__.First'>
<class 'type'>
......@@ -118,7 +118,7 @@ $ ./first_object.py
`object_initialization.py`
```
```py
#!/usr/bin/env python
# object_initialization.py
......@@ -134,7 +134,7 @@ Being()
我们有一个`Being`类。 创建对象后立即自动调用特殊方法`__init__()`
```
```py
$ ./object_initialization.py
Being is initialized
......@@ -148,7 +148,7 @@ Being is initialized
`attributes.py`
```
```py
#!/usr/bin/env python
# attributes.py
......@@ -169,21 +169,21 @@ print(lucky.name)
在此代码示例中,我们有一个`Cat`类。 创建对象后立即自动调用特殊方法`__init__()`
```
```py
def __init__(self, name):
```
类定义中的每个方法都以对实例对象的引用开头。 按照惯例,它的名称为`self``self`名称没有什么特别的。 例如,我们可以这样命名。 第二个参数`name`是自变量。 该值在类初始化期间传递。
```
```py
self.name = name
```
在这里,我们将属性传递给实例对象。
```
```py
missy = Cat('Missy')
lucky = Cat('Lucky')
......@@ -191,7 +191,7 @@ lucky = Cat('Lucky')
在这里,我们创建两个对象:猫 Missy 和 Lucky。 参数的数量必须与类定义的`__init__()`方法相对应。 “ Missy”和“ Lucky”字符串成为`__init__()`方法的`name`参数。
```
```py
print(missy.name)
print(lucky.name)
......@@ -199,7 +199,7 @@ print(lucky.name)
在这里,我们打印两个猫对象的属性。 一个类的每个实例可以有自己的属性。
```
```py
$ ./attributes.py
Missy
Lucky
......@@ -210,7 +210,7 @@ Lucky
`attributes_dynamic.py`
```
```py
#!/usr/bin/env python
# attributes_dynamic.py
......@@ -228,7 +228,7 @@ print("{0} is {1} years old".format(p.name, p.age))
我们定义并创建一个空的`Person`类。
```
```py
p.age = 24
p.name = "Peter"
......@@ -236,7 +236,7 @@ p.name = "Peter"
在这里,我们动态创建两个属性:age 和 name。
```
```py
$ ./attributes_dynamic.py
24 is Peter years old
......@@ -248,7 +248,7 @@ $ ./attributes_dynamic.py
`class_attribute.py`
```
```py
#!/usr/bin/env python
# class_attribute.py
......@@ -275,7 +275,7 @@ print(lucky.__class__.species)
在我们的示例中,我们有两只具有特定`name``age`属性的猫。 两只猫都有一些共同之处。 小姐和幸运者都是哺乳动物。 这反映在类级别属性`species`中。 该属性是在类主体中的任何方法名称之外定义的。
```
```py
print(Cat.species)
print(missy.__class__.species)
......@@ -283,7 +283,7 @@ print(missy.__class__.species)
有两种方法可以访问类对象属性:通过`Cat`类的名称,或借助特殊的`__class__`属性。
```
```py
$ ./class_attribute.py
Missy 3
Lucky 5
......@@ -299,7 +299,7 @@ mammal
`methods.py`
```
```py
#!/usr/bin/env python
# methods.py
......@@ -330,7 +330,7 @@ print(c.area())
在代码示例中,我们有一个`Circle`类。 我们定义了三种新方法。
```
```py
def area(self):
return self.radius * self.radius * Circle.pi
......@@ -338,7 +338,7 @@ def area(self):
`area()`方法返回圆的面积。
```
```py
def setRadius(self, radius):
self.radius = radius
......@@ -346,7 +346,7 @@ def setRadius(self, radius):
`setRadius()`方法为`radius`属性设置新值。
```
```py
def getRadius(self):
return self.radius
......@@ -354,14 +354,14 @@ def getRadius(self):
`getRadius()`方法返回当前半径。
```
```py
c.setRadius(5)
```
在实例对象上调用该方法。 `c`对象与类定义的`self`参数配对。 数字 5 与`radius`参数配对。
```
```py
$ ./methods.py
5
78.5398
......@@ -372,7 +372,7 @@ $ ./methods.py
`bound_unbound_methods.py`
```
```py
#!/usr/bin/env python
# bound_unbound_methods.py
......@@ -394,21 +394,21 @@ print(Methods.getName(m))
在此示例中,我们演示了两个方法调用。
```
```py
print(m.getName())
```
这是绑定的方法调用。 Python 解释器会自动将`m`实例与 self 参数配对。
```
```py
print(Methods.getName(m))
```
这是无界的方法调用。 实例对象已显式提供给`getName()`方法。
```
```py
$ ./bound_unbound_methods.py
Methods
Methods
......@@ -421,7 +421,7 @@ Methods
`inheritance.py`
```
```py
#!/usr/bin/env python
# inheritance.py
......@@ -459,7 +459,7 @@ d.bark()
在此示例中,我们有两个类:`Animal``Dog``Animal`是基类,`Dog`是派生类。 派生类继承基类的功能。 通过`eat()`方法显示。 派生的类修改了基类的现有行为,如`whoAmI()`方法所示。 最后,派生类通过定义新的`bark()`方法来扩展基类的功能。
```
```py
class Dog(Animal):
def __init__(self):
......@@ -471,7 +471,7 @@ class Dog(Animal):
我们将祖先类放在子孙类名称之后的圆括号中。 如果派生类提供了自己的`__init__()`方法,并且我们想调用父构造函数,则必须借助`super`函数显式调用基类`__init__()`方法。
```
```py
$ ./inherit.py
Animal created
Dog created
......@@ -487,7 +487,7 @@ Woof!
`basic_polymorphism.py`
```
```py
#!/usr/bin/env python
# basic_polymorphism.py
......@@ -504,7 +504,7 @@ print(c[3])
Python 在内置类型中广泛使用了多态。 在这里,我们对三种不同的数据类型使用相同的索引运算符。
```
```py
$ ./basic_polymorphism.py
f
2
......@@ -516,7 +516,7 @@ g
`polymorphism.py`
```
```py
#!/usr/bin/env python
# polymorphism.py
......@@ -556,7 +556,7 @@ d.talk()
在这里,我们有两种:狗和猫。 两者都是动物。 `Dog`类和`Cat`类继承了`Animal`类。 它们具有`talk()`方法,可以为它们提供不同的输出。
```
```py
$ ./polymorphism.py
Meow!
Woof!
......@@ -569,7 +569,7 @@ Python 编程语言中的类可以使用特殊的方法名称来实现某些操
`special_methods.py`
```
```py
#!/usr/bin/env python
# special_methods.py
......@@ -607,28 +607,28 @@ del book
在我们的代码示例中,我们有一个 book 类。 在这里,我们介绍四种特殊方法:`__init__()``__str__()``__len__()``__del__()`
```
```py
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
```
在这里,我们称为`__init__()`方法。 该方法创建 Book 类的新实例。
```
```py
print(book)
```
print 关键字调用`__str__()`方法。 此方法应返回对象的非正式字符串表示形式。
```
```py
print(len(book))
```
`len()`函数调用`__len__()`方法。 就我们而言,我们打印书的页数。
```
```py
del book
```
......@@ -639,7 +639,7 @@ del book
`vector.py`
```
```py
#!/usr/bin/env python
# vector.py
......@@ -684,7 +684,7 @@ print(y - x)
该示例介绍了`__add__``__sub__`方法。
```
```py
def __add__(self, other):
data = []
......@@ -699,7 +699,7 @@ def __add__(self, other):
在这里,我们实现向量的加法运算。 当我们使用`+`运算符添加两个`Vector`对象时,将调用`__add__()`方法。 在这里,我们将各个向量的每个成员相加。
```
```py
$ ./vector.py
[4, 2, 5]
[2, -2, -1]
......
......@@ -23,7 +23,7 @@ Python 模块用于组织 Python 代码。 例如,与数据库相关的代码
`empty.py`
```
```py
"""
An empty module
"""
......@@ -34,7 +34,7 @@ An empty module
`test_empty.py`
```
```py
#!/usr/bin/env python
import empty
......@@ -48,7 +48,7 @@ print(sys.__name__)
在此代码示例中,我们导入两个模块:内置模块`sys`和一个自定义模块`empty`。 我们将模块的名称打印到控制台。
```
```py
$ ./test_empty.py
__main__
empty
......@@ -64,7 +64,7 @@ sys
`locating_modules.py`
```
```py
#!/usr/bin/env python
import sys
......@@ -79,28 +79,28 @@ print(textwrap.fill(dnames))
该脚本从`sys.path`变量打印所有目录。
```
```py
import textwrap
```
`textwrap`模块用于轻松设置段落格式。
```
```py
sp = sorted(sys.path)
```
我们从`sys.path`变量中检索目录列表并对它们进行排序。
```
```py
dnames = ', '.join(sp)
```
我们从列表中取出一个字符串。
```
```py
$ ./locating_modules.py
/home/janbodnar/.local/lib/python3.5/site-packages,
/home/janbodnar/PycharmProjects/Simple,
......@@ -117,7 +117,7 @@ gnu, /usr/lib/python3/dist-packages, /usr/lib/python35.zip,
`import`关键字可以以多种方式使用。
```
```py
from module import *
```
......@@ -126,7 +126,7 @@ from module import *
`everything.py`
```
```py
#!/usr/bin/python
from math import *
......@@ -138,7 +138,7 @@ print(pi)
此导入构造已从内置`math`模块导入了所有定义。 我们可以直接调用数学函数,而无需引用`math`模块。
```
```py
$ ./everything.py
-0.9899924966004454
3.141592653589793
......@@ -149,7 +149,7 @@ $ ./everything.py
`pollution.py`
```
```py
#!/usr/bin/env python
from math import *
......@@ -169,7 +169,7 @@ print(pi)
`names.py`
```
```py
#!/usr/bin/env python
"""
......@@ -195,7 +195,7 @@ def _show_version():
`test_names.py`
```
```py
#!/usr/bin/env python
from names import *
......@@ -212,7 +212,7 @@ show_names()
使用`from``import`关键字,可以仅导入某些对象。
```
```py
from module import fun, var
```
......@@ -221,7 +221,7 @@ from module import fun, var
`import_specific.py`
```
```py
#!/usr/bin/python
from math import sin, pi
......@@ -235,7 +235,7 @@ print(pi)
`imnames.py`
```
```py
#!/usr/bin/python
from names import _version, _show_version
......@@ -247,7 +247,7 @@ _show_version()
我们也可以导入下划线开头的定义。 但这是一个不好的做法。
```
```py
$ ./imnames.py
1.0
1.0
......@@ -258,7 +258,7 @@ $ ./imnames.py
最后一种构造使用最广泛。
```
```py
import module
```
......@@ -267,7 +267,7 @@ import module
`impmod.py`
```
```py
#!/usr/bin/env python
import math
......@@ -283,7 +283,7 @@ print(pi)
在这种情况下,我们通过模块名称引用定义。 如我们所见,我们可以使用两个 pi 变量。 我们的定义来自`math`模块。
```
```py
$ ./impmod.py
-0.9899924966004454
3.141592653589793
......@@ -298,7 +298,7 @@ $ ./impmod.py
`importas.py`
```
```py
#!/usr/bin/python
# importas.py
......@@ -312,7 +312,7 @@ print(m.cos(3))
我们可以更改引用模块的名称。 为此,我们使用`as`关键字。
```
```py
$ ./importas.py
3.14159265359
-0.9899924966
......@@ -325,7 +325,7 @@ $ ./importas.py
`importerror.py`
```
```py
#!/usr/bin/env python
try:
......@@ -337,7 +337,7 @@ except ImportError as e:
我们尚未创建`empty2`模块。 因此引发了异常。
```
```py
$ ./importerror.py
Failed to import: No module named empty2
......@@ -353,7 +353,7 @@ Failed to import: No module named empty2
`fibonacci.py`
```
```py
#!/usr/bin/env python
"""
......@@ -379,7 +379,7 @@ if __name__ == '__main__':
通常可以照常导入该模块。 该模块也可以执行。
```
```py
$ ./fibonacci.py
1 1 2 3 5 8 13 21 34 55 89 144 233 377
......@@ -387,7 +387,7 @@ $ ./fibonacci.py
如果确实导入了 fibonacci 模块,则不会自动执行测试。
```
```py
>>> import fibonacci as fib
>>> fib.fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
......@@ -402,7 +402,7 @@ $ ./fibonacci.py
`dirfun.py`
```
```py
#!/usr/bin/env python
"""
......@@ -426,14 +426,14 @@ print(dir())
在此模块中,我们导入两个系统模块。 我们定义一个变量,一个列表和一个函数。
```
```py
print(dir())
```
`dir()`函数返回模块当前名称空间中所有可用的名称。
```
```py
$ ./dirfun.py
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'math', 'names', 'show_names', 'sys', 'version']
......@@ -448,7 +448,7 @@ $ ./dirfun.py
`globalsfun.py`
```
```py
#!/usr/bin/env python
import textwrap
......@@ -467,7 +467,7 @@ print(textwrap.fill(gnames))
我们使用`globals()`功能来打印当前模块的所有全局名称。
```
```py
$ ./globalsfun.py
textwrap, __package__, version, __builtins__, __name__, __spec__,
__doc__, gl, __cached__, myfun, __loader__, __file__
......@@ -482,7 +482,7 @@ __doc__, gl, __cached__, myfun, __loader__, __file__
`animals.py`
```
```py
"""
module animals
"""
......@@ -499,7 +499,7 @@ class Dog:
`mclass.py`
```
```py
#!/usr/bin/env python
from animals import Cat
......@@ -517,14 +517,14 @@ print(c.__module__)
在此代码中,我们使用`__module__`属性。
```
```py
from animals import Cat
```
`animals`模块,我们导入`Cat`类。
```
```py
class Being:
pass
......@@ -532,7 +532,7 @@ class Being:
在当前模块中,我们定义一个类`Being`
```
```py
b = Being()
print(b.__module__)
......@@ -540,7 +540,7 @@ print(b.__module__)
创建`Being`类的实例。 我们打印其模块的名称。
```
```py
c = Cat()
print(c.__module__)
......@@ -548,7 +548,7 @@ print(c.__module__)
我们从`Cat`类创建一个对象。 我们还将在定义模块的位置打印。
```
```py
$ ./mclass.py
__main__
animals
......
......@@ -16,14 +16,14 @@ Python 包是具有通用目的的模块的集合。 软件包目录必须有一
Python 软件包由 Python 软件包管理器`pip`进行管理。
```
```py
$ sudo pip3 install arrow
```
例如,使用上述命令安装了箭头库。
```
```py
$ sudo pip3 uninstall arrow
```
......@@ -34,7 +34,7 @@ $ sudo pip3 uninstall arrow
在第一个示例中,我们使用 Python 创建一个简单的程序包。
```
```py
$ tree
.
├── mymath
......@@ -54,7 +54,7 @@ $ tree
`mfuns.py`
```
```py
def mycube(x):
return x * x * x
......@@ -65,7 +65,7 @@ def mycube(x):
`myprog.py`
```
```py
#!/usr/bin/env python
# myprog.py
......@@ -82,7 +82,7 @@ print(mycube(3))
在下一个示例中,我们在`__init__.py`文件中有一些代码。
```
```py
$ tree
.
├── mymath
......@@ -96,7 +96,7 @@ $ tree
`__init__.py`
```
```py
from .mfuns import mycube
```
......@@ -105,7 +105,7 @@ from .mfuns import mycube
`mfuns.py`
```
```py
def mycube(x):
return x * x * x
......@@ -116,7 +116,7 @@ def mycube(x):
`myprog.py`
```
```py
#!/usr/bin/env python
# myprog.py
......@@ -133,7 +133,7 @@ print(mycube(3))
从 Python 3.3 开始,无需使用`__init__.py`文件就可以定义软件包目录。
```
```py
read.py
constants/
data.py
......@@ -144,7 +144,7 @@ constants/
`data.py`
```
```py
colours = ('yellow', 'blue', 'red', 'orange', 'brown')
names = ('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
......@@ -154,7 +154,7 @@ names = ('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
`read.py`
```
```py
#!/usr/bin/env python
# read.py
......@@ -169,7 +169,7 @@ print(mydata.names)
`read.py`脚本中,我们导入元组并将其打印到终端。
```
```py
$ ./read.py
('yellow', 'blue', 'red', 'orange', 'brown')
('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
......@@ -180,7 +180,7 @@ $ ./read.py
`arrow`是用于在 Python 中处理日期和时间的第三方库。
```
```py
$ ls /usr/local/lib/python3.5/dist-packages/arrow
api.py arrow.py factory.py formatter.py __init__.py
locales.py parser.py __pycache__ util.py
......@@ -193,7 +193,7 @@ locales.py parser.py __pycache__ util.py
我们还可以创建子包。 要访问子包,我们使用点运算符。
```
```py
$ tree
.
├── constants
......@@ -210,7 +210,7 @@ $ tree
`constants/__init__.py`
```
```py
from .data import names
```
......@@ -219,7 +219,7 @@ from .data import names
`constants/data.py`
```
```py
names = ('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
```
......@@ -228,7 +228,7 @@ names = ('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
`numbers/__init__.py`
```
```py
from .myintegers import myintegers
```
......@@ -237,7 +237,7 @@ from .myintegers import myintegers
`numbers/myintegers.py`
```
```py
myintegers = (2, 3, 45, 6, 7, 8, 9)
```
......@@ -246,7 +246,7 @@ myintegers = (2, 3, 45, 6, 7, 8, 9)
`read.py`
```
```py
#!/usr/bin/env python
# read.py
......@@ -261,7 +261,7 @@ print(myintegers)
这是`read.py`程序。 我们从`constants`包中导入`names`元组,并从`constants.numbers`子包中导入`myintegers`元组。
```
```py
$ ./read.py
('Jack', 'Jessica', 'Robert', 'Lucy', 'Tom')
(2, 3, 45, 6, 7, 8, 9)
......
......@@ -10,7 +10,7 @@
在 Python 中,我们具有以下语法来处理异常:
```
```py
try:
# do something
......@@ -39,7 +39,7 @@ finally:
`zero_division.py`
```
```py
#!/usr/bin/env python
# zero_division.py
......@@ -57,7 +57,7 @@ print(f"{x} / {y} is {x/y}")
在此脚本中,我们从控制台获得两个数字。 我们将这两个数相除。 如果第二个数字为零,则会出现异常。
```
```py
Enter first number:3
Enter second number:0
Traceback (most recent call last):
......@@ -71,7 +71,7 @@ ZeroDivisionError: float division by zero
`zero_division2.py`
```
```py
#!/usr/bin/env python
# zero_division2.py
......@@ -100,7 +100,7 @@ while True:
首先,我们仅检查`y`的值不为零。 如果`y`值为零,我们将打印警告消息并再次重复输入周期。 这样我们就可以处理错误,并且脚本不会中断。
```
```py
$ ./zero_division2.py
Enter first number:4
Enter second number:0
......@@ -118,7 +118,7 @@ Enter second number:6
`zero_division3.py`
```
```py
#!/usr/bin/env python
# zerodivision3.py
......@@ -143,7 +143,7 @@ except ZeroDivisionError:
我们将代码放置在`try`关键字之后我们期望发生异常的位置。 如果引发了`except`关键字,则捕获该异常。 异常类型在`except`关键字之后指定。
```
```py
except ValueError:
pass
except (IOError, OSError):
......@@ -159,7 +159,7 @@ except (IOError, OSError):
`value_error.py`
```
```py
#!/usr/bin/env python
# value_error.py
......@@ -184,7 +184,7 @@ except ValueError as e:
在该示例中,我们有一个读取年龄作为用户输入的函数。 当用户提供不正确的值时,我们将引发`ValueError`异常。
```
```py
if age < 0 or age > 130:
raise ValueError("Invalid age")
......@@ -200,7 +200,7 @@ return age
`multiple_exceptions.py`
```
```py
#!/usr/bin/env python
# multiple_exceptions.py
......@@ -221,14 +221,14 @@ except (FileExistsError, RuntimeError) as e:
该代码示例在一个`except`语句中捕获了两个异常:`FileExistsError``RuntimeError`
```
```py
os.mkdir('newdir')
```
使用`os.mkdir()`方法创建一个新目录。 如果目录已经存在,则触发`FileExistsError`
```
```py
raise RuntimeError("Runtime error occurred")
```
......@@ -241,7 +241,7 @@ raise RuntimeError("Runtime error occurred")
`exception_as.py`
```
```py
#!/usr/bin/env python
# exception_argument.py
......@@ -259,7 +259,7 @@ except IndexError as e:
从异常对象中,我们可以获取错误消息或类名。
```
```py
$ ./exception_as.py
tuple index out of range
Class: <class 'IndexError'>
......@@ -272,7 +272,7 @@ Class: <class 'IndexError'>
`interrupt.py`
```
```py
#!/usr/bin/env python
# interrupt.py
......@@ -289,7 +289,7 @@ except KeyboardInterrupt:
脚本开始并不断循环。 如果按 `Ctrl` + `C` ,我们将中断循环。 在这里,我们捕获了`KeyboardInterrupt`异常。
```
```py
Exception
BaseException
KeyboardInterrupt
......@@ -300,7 +300,7 @@ Exception
`interrupt2.py`
```
```py
#!/usr/bin/env python
# interrupt2.py
......@@ -323,7 +323,7 @@ except BaseException:
`user_defined.py`
```
```py
#!/usr/bin/env python
# user_defined.py
......@@ -355,7 +355,7 @@ for i in string:
在我们的代码示例中,我们创建了一个新的异常。 异常是从基类`Exception`派生的。 如果在字符串中发现字母 b 的任何出现,我们将`raise`作为异常。
```
```py
$ ./user_defined.py
'BFoundEx: b character found at position 10'
......@@ -367,7 +367,7 @@ $ ./user_defined.py
`cleanup.py`
```
```py
#!/usr/bin/env python
# cleanup.py
......@@ -401,7 +401,7 @@ finally:
`stacktrace_ex.py`
```
```py
#!/usr/bin/env python
# stacktrace_ex.py
......@@ -434,14 +434,14 @@ test()
在示例中,我们在嵌套的`myfun2`函数中将除以零的异常。
```
```py
for line in traceback.format_stack():
```
`format_stack()`从当前堆栈帧中提取原始回溯并将其格式化为元组列表。 我们使用 for 循环遍历元组列表。
```
```py
$ ./stacktrace_ex.py
division by zero
Class: <class 'ZeroDivisionError'>
......
......@@ -16,7 +16,7 @@ Python 有几个内置对象,它们实现了迭代器协议。 例如列表,
`iterator.py`
```
```py
#!/usr/bin/env python
# iterator.py
......@@ -40,7 +40,7 @@ print(list(it))
在代码示例中,我们显示了字符串上的内置迭代器。 在 Python 中,字符串是不可变的字符序列。 `iter()`函数返回对象的迭代器。 我们还可以在迭代器上使用`list()``tuple()`函数。
```
```py
$ ./iterator.py
f o r m i d a b l e
f
......@@ -56,7 +56,7 @@ r
`read_data.py`
```
```py
#!/usr/bin/env python
# read_data.py
......@@ -79,7 +79,7 @@ with open('data.txt', 'r') as f:
`read_data_iterator.py`
```
```py
#!/usr/bin/env python
# read_data_iterator.py
......@@ -99,7 +99,7 @@ with open('data.txt', 'r') as f:
`iterator_protocol.py`
```
```py
#!/usr/bin/env python
# iterator_protocol.py
......@@ -134,7 +134,7 @@ for e in s:
在代码示例中,我们创建了一个数字序列 1,4,27,256,...。 这表明使用迭代器,我们可以处理无限序列。
```
```py
def __iter__(self):
return self
......@@ -143,7 +143,7 @@ def __iter__(self):
for 语句在容器对象上调用`__iter__()`函数。 该函数返回一个定义方法`__next__()`的迭代器对象,该方法一次访问一个容器中的元素。
```
```py
def next(self):
self.x += 1
return self.x**self.x
......@@ -152,7 +152,7 @@ for 语句在容器对象上调用`__iter__()`函数。 该函数返回一个定
`next()`方法返回序列的下一个元素。
```
```py
if n > 10:
break
......@@ -160,7 +160,7 @@ if n > 10:
因为我们正在处理无限序列,所以我们必须中断 for 循环。
```
```py
$ ./iterator.py
1
4
......@@ -182,7 +182,7 @@ $ ./iterator.py
`stopiter.py`
```
```py
#!/usr/bin/env python
# stopiter.py
......@@ -213,7 +213,7 @@ for e in s:
该代码示例将打印序列的前 14 个数字。
```
```py
if self.x > 14:
raise StopIteration
......@@ -221,7 +221,7 @@ if self.x > 14:
`StopIteration`异常将停止 for 循环。
```
```py
$ ./stop_iter.py
1
4
......@@ -257,7 +257,7 @@ Python 中的生成器:
`simple_generator.py`
```
```py
#!/usr/bin/env python
# simple_generator.py
......@@ -285,7 +285,7 @@ except StopIteration:
该程序将创建一个非常简单的生成器。
```
```py
def gen():
x, y = 1, 2
......@@ -298,7 +298,7 @@ def gen():
就像正常函数一样,生成器使用`def`关键字定义。 我们在生成器主体内使用两个`yield`关键字。 `yield`关键字退出生成器并返回一个值。 下次调用迭代器的`next()`函数时,我们在`yield`关键字之后的行继续。 请注意,局部变量会在整个迭代过程中保留。 当没有余量可产生时,将引发`StopIteration`异常。
```
```py
$ ./generator.py
(1, 2)
(2, 2)
......@@ -310,7 +310,7 @@ Iteration finished
`fibonacci_gen.py`
```
```py
#!/usr/bin/env python
# fibonacci_gen.py
......@@ -347,7 +347,7 @@ except KeyboardInterrupt:
`generator_expression.py`
```
```py
#!/usr/bin/env python
# generator_expression.py
......@@ -368,14 +368,14 @@ for e in n:
该示例计算的值可以除以 3,而没有余数。
```
```py
n = (e for e in range(50000000) if not e % 3)
```
将使用圆括号创建生成器表达式。 在这种情况下,创建列表推导式将非常低效,因为该示例将不必要地占用大量内存。 为此,我们创建了一个生成器表达式,该表达式根据需要延迟生成值。
```
```py
i = 0
for e in n:
......@@ -394,7 +394,7 @@ for e in n:
`roman_empire.txt`
```
```py
The Roman Empire (Latin: Imperium Rōmānum; Classical Latin: [ɪmˈpɛ.ri.ũː roːˈmaː.nũː]
Koine and Medieval Greek: Βασιλεία τῶν Ῥωμαίων, tr. Basileia tōn Rhōmaiōn) was the
post-Roman Republic period of the ancient Roman civilization, characterized by government
......@@ -416,7 +416,7 @@ the new title Augustus, effectively marking the end of the Roman Republic.
`generator_expression.py`
```
```py
#!/usr/bin/env python
# gen_grep.py
......@@ -439,7 +439,7 @@ with open(file_name, 'r') as f:
该示例从文件中读取数据,并打印包含指定模式及其行号的行。
```
```py
def grep(pattern, lines):
return ((line, lines.index(line)+1) for line in lines if pattern in line)
......@@ -447,7 +447,7 @@ def grep(pattern, lines):
类似于 grep 的实用程序使用此生成器表达式。 该表达式遍历行列表并选择包含模式的行。 它计算列表中该行的索引,即它在文件中的行号。
```
```py
with open(file_name, 'r') as f:
lines = f.readlines()
......@@ -458,7 +458,7 @@ with open(file_name, 'r') as f:
我们打开文件进行读取,然后对数据调用`grep()`函数。 该函数返回一个生成器,该生成器通过 for 循环遍历。
```
```py
$ ./gen_grep.py Roman roman_empire.txt
1 The Roman Empire (Latin: Imperium Rōmānum; Classical Latin: [ɪmˈpɛ.ri.ũː roːˈmaː.nũː]
3 post-Roman Republic period of the ancient Roman civilization, characterized by government
......
......@@ -10,7 +10,7 @@
`dir()`函数返回属于对象的属性和方法的排序列表。
```
```py
>>> dir(())
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
......@@ -23,7 +23,7 @@
在这里,我们看到了元组对象的`dir()`函数的输出。
```
```py
>>> print(().__doc__)
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items
......@@ -36,7 +36,7 @@ If the argument is a tuple, the return value is the same object.
`direx.py`
```
```py
#!/usr/bin/env python
# direx.py
......@@ -68,7 +68,7 @@ print(dir("String"))
不带任何参数的`dir()`返回当前作用域中的名称。
```
```py
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> import sys
......@@ -86,7 +86,7 @@ print(dir("String"))
`typefun.py`
```
```py
#!/usr/bin/env python
# typefun.py
......@@ -118,7 +118,7 @@ print(type(sys))
该示例将各种类型的对象打印到控制台屏幕。
```
```py
$ ./typefun.py
<class 'int'>
<class 'str'>
......@@ -141,7 +141,7 @@ $ ./typefun.py
`idfun.py`
```
```py
#!/usr/bin/env python
# idfun.py
......@@ -171,7 +171,7 @@ print(id(object))
该代码示例打印内置和自定义的各种对象的 ID。
```
```py
$ ./idfun.py
10914368
139696088742576
......@@ -189,7 +189,7 @@ $ ./idfun.py
`sys`模块提供对解释器使用或维护的系统特定变量和功能以及与解释器强烈交互的功能的访问。 该模块允许我们查询有关 Python 环境的信息。
```
```py
>>> import sys
>>> sys.version
'3.5.2 (default, Nov 17 2016, 17:05:23) \n[GCC 5.4.0 20160609]'
......@@ -206,7 +206,7 @@ $ ./idfun.py
我们还可以使用`dir()`函数来获取`sys`模块的变量和函数的完整列表。
```
```py
>>> sys.executable
'/usr/bin/python3'
>>> sys.argv
......@@ -218,7 +218,7 @@ $ ./idfun.py
该示例显示了`sys`模块的`executable``argv``byteorder`属性。
```
```py
>>> sys.executable
'/usr/bin/python3'
......@@ -226,7 +226,7 @@ $ ./idfun.py
可执行文件是一个字符串,给出有意义的系统上 Python 解释器的可执行二进制文件的名称。
```
```py
>>> sys.argv
['']
......@@ -234,7 +234,7 @@ $ ./idfun.py
这给出了传递给 Python 脚本的命令行参数列表。
```
```py
>>> sys.byteorder
'little'
......@@ -248,7 +248,7 @@ $ ./idfun.py
`attrs.py`
```
```py
#!/usr/bin/env python
# attr.py
......@@ -267,7 +267,7 @@ print(getattr(fun, '__doc__'))
`hasattr()`函数检查对象是否具有属性。 `getattr()`函数返回属性的内容(如果有的话)。
```
```py
$ ./attr.py
True
True
......@@ -279,7 +279,7 @@ None
`isinstance`函数检查对象是否为特定类的实例。
```
```py
>>> print(isinstance.__doc__)
Return whether an object is an instance of a class or of a subclass thereof.
......@@ -293,7 +293,7 @@ or ...`` etc.
`instance.py`
```
```py
#!/usr/bin/env python
# instance.py
......@@ -314,7 +314,7 @@ print(isinstance('str', str))
众所周知,一切都是 Python 中的对象; 偶数和字符串。 `object`是 Python 中所有对象的基本类型。
```
```py
$ ./instance.py
True
True
......@@ -327,7 +327,7 @@ True
`subclass.py`
```
```py
#!/usr/bin/env python
# subclass.py
......@@ -351,7 +351,7 @@ print(issubclass(Wall, Wall))
在我们的代码示例中,`Wall`类是`Object`类的子类。 `Object``Wall`本身也是它们的子类。 `Object`类不是`Wall`类的子类。
```
```py
$ ./subclass.py
True
False
......@@ -364,7 +364,7 @@ True
`namedoc.py`
```
```py
#!/usr/bin/env python
# namedoc.py
......@@ -385,7 +385,7 @@ for i in funcs:
在我们的示例中,我们创建了三个函数的列表:一个自定义函数和两个本机函数。 我们浏览列表并打印`__name__``__doc__`属性。
```
```py
$ ./namedoc.py
noaction
A function, which does nothing
......@@ -414,7 +414,7 @@ errors defaults to 'strict'.
`callable.py`
```
```py
#!/usr/bin/env python
# callable.py
......@@ -438,7 +438,7 @@ print(callable(1))
在代码示例中,我们检查三个对象是否可调用。
```
```py
print(callable(fun))
print(callable(c.setName))
......@@ -446,7 +446,7 @@ print(callable(c.setName))
`fun()`函数和`setName()`方法是可调用的。 (方法是绑定到对象的函数。)
```
```py
$ ./callable.py
True
True
......
......@@ -12,14 +12,14 @@ Faker 是一个生成伪造数据的 Python 库。 Faka 数据通常用于测试
该软件包随 composer 一起安装。
```
```py
$ pip install Faker
```
我们安装了 Faker 模块。
```
```py
$ pip install Dumper
```
......@@ -38,7 +38,7 @@ Faker 将数据生成委托给提供者。 默认提供程序使用英语语言
`simple.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -54,7 +54,7 @@ print(f'text: {faker.text()}')
该示例输出假名称,地址和文本。
```
```py
$ ./simple.py
name: Arthur Patton
address: 0638 Larsen Way
......@@ -73,7 +73,7 @@ Laugh sport necessary tree. As during day up fall.
`names.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -93,7 +93,7 @@ print(f'Female name: {faker.name_female()}')
该示例创建假的全名,男性的姓氏和姓氏。
```
```py
$ ./names.py
Name: Tara Brown
First name: Stephanie
......@@ -112,7 +112,7 @@ Female name: Lacey Roberts
`jobs.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -126,7 +126,7 @@ for _ in range(6):
该示例创建了六个伪造作业。
```
```py
$ ./jobs.py
Town planner
Paediatric nurse
......@@ -145,7 +145,7 @@ Faker 在某种程度上支持本地化数据。 语言环境被传递给构造
`localized.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -164,7 +164,7 @@ for i in range(3):
该示例使用捷克语生成伪造数据。
```
```py
$ ./localized.py
Irena Novotná, Nad Šancemi 725
055 80 Bojkovice, 606 136 053
......@@ -183,7 +183,7 @@ Klára Moravcová, Neužilova 6/3
`currencies.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -199,7 +199,7 @@ print(f'currency code: {faker.currency_code()}')
该程序生成假货币。
```
```py
$ ./currencies.py
currency: ('ISK', 'Icelandic króna')
currency name: Israeli new shekel
......@@ -215,7 +215,7 @@ Faker 允许创建假单词。
`words.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -233,21 +233,21 @@ print(f'customized unique words: {faker.words(3, words, True)}')
该示例创建伪单词。
```
```py
print(f'a word: {faker.word()}')
```
该行生成一个伪造的单词。
```
```py
print(f'six words: {faker.words(6)}')
```
在这里,我们生成六个伪单词。
```
```py
words = ['forest', 'blue', 'cloud', 'sky', 'wood', 'falcon']
print(f'customized unique words: {faker.words(3, words, True)}')
......@@ -256,7 +256,7 @@ print(f'customized unique words: {faker.words(3, words, True)}')
我们还可以从预定义的单词列表中创建假单词。
```
```py
$ words.py
a word: show
six words: ['value', 'its', 'those', 'wish', 'enter', 'hold']
......@@ -272,7 +272,7 @@ Faker 可以使用`simple_profile()`创建简单的虚拟配置文件,并使
`profiles.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -297,7 +297,7 @@ dumper.dump(profile3)
该示例为男性和女性创建虚拟概要文件。
```
```py
$ ./profiles.py
<dict at 0x20d590a7678>:
username: 'gmorgan'
......@@ -342,7 +342,7 @@ Faker 允许生成随机数字和整数。
`fake_numbers.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -357,14 +357,14 @@ print(f'Random digit: {faker.random_digit()}')
该示例生成随机数字和整数。
```
```py
print(f'Random int: {faker.random_int(0, 100)}')
```
我们可以在`random_int()`方法中指定界限。
```
```py
$ ./fake_numbers.py
Random int: 5181
Random int: 91
......@@ -380,7 +380,7 @@ Random digit: 9
`hash_uuid.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -396,7 +396,7 @@ print(f'uuid4: {faker.uuid4()}')
该示例生成三个假哈希和一个 uuid 值。
```
```py
$ ./hash_uuid.py
md5: aace57d56794686acec9eb190d401d46
sha1: 9f8f6af3089e7b5ed571591701afcfd9c2bb7a0e
......@@ -413,7 +413,7 @@ Faker 有多个用于伪造与 Internet 相关的数据的访问器。
`internet.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -447,7 +447,7 @@ print(f'Image URL: {faker.image_url()}')
该示例显示了各种与 Internet 相关的数据,包括电子邮件,域名,信息,IP 地址和 URL。
```
```py
$ ./internet.py
Email: hescobar@acevedo.info
Safe email: jonesgregory@example.net
......@@ -476,7 +476,7 @@ Faker 有很多伪造日期和时间值的方法。
`date_time.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -497,7 +497,7 @@ print(f'AM/PM: {faker.am_pm()}')
第一个示例显示了伪造的生日,日期时间部分,时区和 AM / PM 方法。
```
```py
$ date_time.py
Date of birth: 2008-08-07
Century: IV
......@@ -515,7 +515,7 @@ AM/PM: AM
`datetime2.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -547,7 +547,7 @@ for val in series:
第二个示例显示了用于生成当前世纪,十年,年份或月份中的日期时间值的方法。 它还包括时间序列值的生成。
```
```py
$ date_time2.py
Datetime this century: 2013-08-06 23:42:47
Datetime this decade: 2010-02-15 01:08:34
......@@ -572,7 +572,7 @@ Date this month: 2019-04-04
`datetime3.py`
```
```py
#!/usr/bin/env python
from faker import Faker
......@@ -601,7 +601,7 @@ print(f"Past date: {faker.past_date()}")
第三个示例显示了用于各种日期时间格式,获取选定范围的日期时间值以及生成未来或过去值的方法。
```
```py
$ date_time3.py
Unix time: 1389138339
Datetime: 1988-01-24 09:16:09
......@@ -625,7 +625,7 @@ Past date: 2019-03-22
在以下示例中,我们使用 Faker 和 Jinja2 模板生成 XML 数据。 XML 文件将包含用户。
```
```py
$ pip install jinja2
```
......@@ -634,7 +634,7 @@ $ pip install jinja2
`fake_xml.py`
```
```py
#!/usr/bin/env python3
from jinja2 import Environment, FileSystemLoader
......@@ -675,7 +675,7 @@ print(output, file=open('users.xml', 'w'))
`templates/users.xml.j2`
```
```py
<?xml version="1.0" encoding="UTF-8"?>
<users>
{% for user in users %}
......
......@@ -18,7 +18,7 @@ f 字符串的前缀为`f`,并使用`{}`括号评估值。
`formatting_strings.py`
```
```py
#!/usr/bin/env python3
name = 'Peter'
......@@ -32,28 +32,28 @@ print(f'{name} is {age} years old')
该示例使用两个变量设置字符串格式。
```
```py
print('%s is %d years old' % (name, age))
```
这是最旧的选项。 它使用`%`运算符和经典字符串格式指定,例如`%s``%d`
```
```py
print('{} is {} years old'.format(name, age))
```
从 Python 3.0 开始,`format()`函数被引入以提供高级格式化选项。
```
```py
print(f'{name} is {age} years old')
```
从 Python 3.6 开始,Python f 字符串可用。 该字符串具有`f`前缀,并使用`{}`评估变量。
```
```py
$ python formatting_string.py
Peter is 23 years old
Peter is 23 years old
......@@ -69,7 +69,7 @@ Peter is 23 years old
`expressions.py`
```
```py
#!/usr/bin/env python3
bags = 3
......@@ -81,7 +81,7 @@ print(f'There are total of {bags * apples_in_bag} apples')
该示例对 f 字符串中的表达式求值。
```
```py
$ python expressions.py
There are total of 36 apples
......@@ -95,7 +95,7 @@ There are total of 36 apples
`dicts.py`
```
```py
#!/usr/bin/env python3
user = {'name': 'John Doe', 'occupation': 'gardener'}
......@@ -106,7 +106,7 @@ print(f"{user['name']} is a {user['occupation']}")
该示例以 f 字符串形式评估字典。
```
```py
$ python dicts.py
John Doe is a gardener
......@@ -120,7 +120,7 @@ John Doe is a gardener
`multiline.py`
```
```py
#!/usr/bin/env python3
name = 'John Doe'
......@@ -139,7 +139,7 @@ print(msg)
该示例显示了多行 f 字符串。 F 弦放在方括号之间; 每个字符串前面都带有`f`字符。
```
```py
$ python multiline.py
Name: John Doe
Age: 32
......@@ -155,7 +155,7 @@ Occupation: gardener
`call_function.py`
```
```py
#!/usr/bin/env python3
def mymax(x, y):
......@@ -171,7 +171,7 @@ print(f'Max of {a} and {b} is {mymax(a, b)}')
该示例在 f 字符串中调用自定义函数。
```
```py
$ python call_fun.py
Max of 3 and 4 is 4
......@@ -185,7 +185,7 @@ Python f 字符串也接受对象。 对象必须定义了`__str__()`或`__repr_
`objects.py`
```
```py
#!/usr/bin/env python3
class User:
......@@ -204,7 +204,7 @@ print(f'{u}')
该示例评估 f 字符串中的对象。
```
```py
$ python objects.py
John Doe is a gardener
......@@ -218,7 +218,7 @@ John Doe is a gardener
`escaping.py`
```
```py
#!/usr/bin/env python3
print(f'Python uses {{}} to evaludate variables in f-strings')
......@@ -228,7 +228,7 @@ print(f'This was a \'great\' film')
为了避免花括号,我们将字符加倍。 单引号以反斜杠字符转义。
```
```py
$ python escaping.py
Python uses {} to evaludate variables in f-strings
This was a 'great' film
......@@ -243,7 +243,7 @@ This was a 'great' film
`format_datetime.py`
```
```py
#!/usr/bin/env python3
import datetime
......@@ -256,7 +256,7 @@ print(f'{now:%Y-%m-%d %H:%M}')
该示例显示格式化的当前日期时间。 日期时间格式说明符位于&lt;colon&gt;&lt;/colon&gt;字符之后。
```
```py
$ python format_datetime.py
2019-05-11 22:39
......@@ -270,7 +270,7 @@ $ python format_datetime.py
`format_floats.py`
```
```py
#!/usr/bin/env python3
val = 12.3
......@@ -282,7 +282,7 @@ print(f'{val:.5f}')
该示例打印格式化的浮点值。
```
```py
$ python format_floats.py
12.30
12.30000
......@@ -297,7 +297,7 @@ $ python format_floats.py
`format_width.py`
```
```py
#!/usr/bin/env python3
for x in range(1, 11):
......@@ -307,7 +307,7 @@ for x in range(1, 11):
该示例打印三列。 每个列都有一个预定义的宽度。 第一列使用 0 填充较短的值。
```
```py
$ python format_width.py
01 1 1
02 4 8
......@@ -330,7 +330,7 @@ $ python format_width.py
`justify.py`
```
```py
#!/usr/bin/env python3
s1 = 'a'
......@@ -347,7 +347,7 @@ print(f'{s4:>10}')
我们有四个不同长度的弦。 我们将输出的宽度设置为十个字符。 值在右对齐。
```
```py
$ python justify.py
a
ab
......@@ -364,7 +364,7 @@ $ python justify.py
`format_notations.py`
```
```py
#!/usr/bin/env python3
a = 300
......@@ -382,7 +382,7 @@ print(f"{a:e}")
该示例以三种不同的表示法打印值。
```
```py
$ python format_notations.py
12c
454
......
......@@ -34,7 +34,7 @@ bcrypt 算法使用强大的加密技术为我们创建哈希并加盐。 该算
`create_hashed_password.py`
```
```py
#!/usr/bin/env python3
import bcrypt
......@@ -51,28 +51,28 @@ print(hashed)
该示例使用 bcrypt 创建一个 salt 和一个哈希密码。
```
```py
import bcrypt
```
我们导入`bcrypt`模块。
```
```py
salt = bcrypt.gensalt()
```
`gensalt()`功能生成盐。
```
```py
hashed = bcrypt.hashpw(passwd, salt)
```
使用`hashpw()`函数创建一个哈希值,该函数将明文值和盐作为参数。
```
```py
$ python first.py
b'$2b$12$mwSIOyxLJid1jFLgnU0s0.'
b'$2b$12$mwSIOyxLJid1jFLgnU0s0.7pmzp8Mtx.GEO30x0AbI2v8r2sb98Cy'
......@@ -90,7 +90,7 @@ b'$2b$12$MgGs11HIXGkg1Bm1Epw0Du20TV8ppi2Latgq7kKng8UjM5ZFWKKeS'
`check_passwd.py`
```
```py
#!/usr/bin/env python3
import bcrypt
......@@ -109,7 +109,7 @@ else:
使用`checkpw()`功能检查密码。
```
```py
$ python check_passwd.py
match
......@@ -123,7 +123,7 @@ match
`cost_factor.py`
```
```py
#!/usr/bin/env python3
import bcrypt
......@@ -144,7 +144,7 @@ print(hashed)
我们使用`rounds`参数将成本因子设置为 16。 我们测量生成 passowrd 哈希的时间。
```
```py
$ cost_factor.py
4.268407821655273
b'$2b$16$.1FczuSNl2iXHmLojhwBZO9vCfA5HIqrONkefhvn2qLQpth3r7Jwe'
......
......@@ -35,7 +35,7 @@ TCP / IP 是设备用于在 Internet 和大多数本地网络上进行通信的
`get_ip.py`
```
```py
#!/usr/bin/env python
import socket
......@@ -47,7 +47,7 @@ print(ip)
该示例打印`example.com`的 IP 地址。
```
```py
$ ./get_ip.py
93.184.216.34
......@@ -61,7 +61,7 @@ UDP 是一种通信协议,它通过网络传输独立的数据包,不保证
`qotd_client.py`
```
```py
#!/usr/bin/env python
import socket
......@@ -80,56 +80,56 @@ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
该示例创建一个连接到 QOTD 服务的客户端程序。
```
```py
import socket
```
我们导入`socket`模块。
```
```py
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
```
创建了用于 IPv4 的数据报套接字。
```
```py
message = b''
```
我们发送空消息; QOTD 服务通过向套接字发送任意数据来工作; 它只是用引号引起来。 为了通过 TCP / UDP 进行通信,我们使用二进制字符串。
```
```py
addr = ("djxmmx.net", 17)
```
我们提供地址和端口。
```
```py
s.sendto(message, addr)
```
我们使用`sendto()`方法发送数据。
```
```py
data, address = s.recvfrom(1024)
```
UDP 套接字使用`recvfrom()`接收数据。 它的参数是缓冲区大小。 返回值是一对(数据,地址),其中数据是代表接收到的数据的字节字符串,而地址是发送数据的套接字的地址。
```
```py
print(data.decode())
```
我们将解码后的数据打印到终端。
```
```py
$ ./qotd_client.py
"Oh the nerves, the nerves; the mysteries of this machine called man!
Oh the little that unhinges it, poor creatures that we are!"
......@@ -147,7 +147,7 @@ $ ./qotd_client.py
`time_client.py`
```
```py
#!/usr/bin/env python
import socket
......@@ -165,14 +165,14 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
该示例通过连接到时间服务器的 TCP 套接字来确定当前时间。
```
```py
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
```
创建用于 IPv4 的 TCP 套接字。
```
```py
host = "time.nist.gov"
port = 13
......@@ -180,21 +180,21 @@ port = 13
这是工作时间服务器的主机名和端口号。
```
```py
s.connect((host, port))
```
我们使用`connect()`连接到远程套接字。
```
```py
s.sendall(b'')
```
`sendall()`方法将数据发送到套接字。 套接字必须连接到远程套接字。 它继续从字节发送数据,直到发送完所有数据或发生错误为止。
```
```py
print(str(s.recv(4096), 'utf-8'))
```
......@@ -207,7 +207,7 @@ HEAD 请求是没有消息正文的 GET 请求。 请求/响应的标头包含
`head_request.py`
```
```py
#!/usr/bin/env python
import socket
......@@ -222,14 +222,14 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
在示例中,我们向`webcode.me`发送 HEAD 请求。
```
```py
s.sendall(b"HEAD / HTTP/1.1\r\nHost: webcode.me\r\nAccept: text/html\r\n\r\n")
```
`HEAD`命令发出头请求,后跟资源 URL 和 HTTP 协议版本。 请注意,`\r\n`是通信过程中必不可少的部分。 在 [RFC 7231](https://tools.ietf.org/html/rfc7231) 文档中描述了详细信息。
```
```py
$ head_request.py
HTTP/1.1 200 OK
Server: nginx/1.6.2
......@@ -251,7 +251,7 @@ HTTP GET 方法请求指定资源的表示形式。 使用 GET 的请求应仅
`get_request.py`
```
```py
#!/usr/bin/env python
import socket
......@@ -274,14 +274,14 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
该示例使用 GET 请求读取`webcode.me`的主页。
```
```py
s.sendall(b"GET / HTTP/1.1\r\nHost: webcode.me\r\nAccept: text/html\r\nConnection: close\r\n\r\n")
```
对于 HTTP 1.1 协议,默认情况下,连接可以是持久的。 这就是为什么我们发送`Connection: close`标头的原因。
```
```py
while True:
data = s.recv(1024)
......@@ -295,7 +295,7 @@ while True:
我们使用 while 循环来处理接收到的数据。 如果没有错误发生,则`recv()`返回接收到的字节。 如果连接已正常关闭,则返回值为空字节字符串。 `recv()`是一种阻止方法,直到完成它,或者达到超时或发生另一个异常为止。
```
```py
$ ./get_request.py
HTTP/1.1 200 OK
Server: nginx/1.6.2
......@@ -338,7 +338,7 @@ Accept-Ranges: bytes
`echo_server.py`
```
```py
#!/usr/bin/env python
import socket
......@@ -371,7 +371,7 @@ with socket.socket() as s:
回显服务器将客户端消息发送回客户端。
```
```py
host = 'localhost'
port = 8001
......@@ -379,21 +379,21 @@ port = 8001
服务器在端口 8001 上的 localhost 上运行。
```
```py
s.bind((host, port))
```
`bind()`方法建立通信端点。 它将套接字绑定到指定的地址。 套接字必须尚未绑定。 (地址的格式取决于地址系列。)
```
```py
s.listen()
```
`listen()`方法使服务器可以接受连接。 服务器现在可以侦听套接字上的连接。 `listen()`具有`backlog`参数。 它指定系统在拒绝新连接之前允许的不可接受的连接数。 自 Python 3.5 起,此参数是可选的。 如果未指定,则选择默认的积压值。
```
```py
con, addr = s.accept()
```
......@@ -404,7 +404,7 @@ con, addr = s.accept()
`echo_client.py`
```
```py
#!/usr/bin/env python
import socket
......@@ -428,7 +428,7 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
`async_server.py`
```
```py
#!/usr/bin/env python
# from threading import current_thread
......@@ -450,7 +450,7 @@ loop.run_forever()
现在,我们可以测试阻塞服务器和非阻塞服务器的性能。
```
```py
$ ab -c 50 -n 1000 http://localhost:8001/
```
......
......@@ -22,7 +22,7 @@ Python smtplib 教程展示了如何使用 smtplib 模块在 Python 中发送电
## 使用 Python 内置邮件服务器
```
```py
$ python -m smtpd -c DebuggingServer -n localhost:1025
```
......@@ -31,7 +31,7 @@ $ python -m smtpd -c DebuggingServer -n localhost:1025
`built_in.py`
```
```py
#!/usr/bin/env python
import smtplib
......@@ -57,7 +57,7 @@ with smtplib.SMTP('localhost', port) as server:
我们向本地开发邮件服务器发送一条简单的文本消息。
```
```py
sender = 'admin@example.com'
receivers = ['info@example.com']
......@@ -65,7 +65,7 @@ receivers = ['info@example.com']
我们提供发送者和接收者。 `example.com`是专门用于文档中的说明性示例的域名。
```
```py
msg = MIMEText('This is test mail')
msg['Subject'] = 'Test mail'
......@@ -76,7 +76,7 @@ msg['To'] = 'info@example.com'
`MimeText`用于发送文本电子邮件。 我们提供主题,从选项到选项。
```
```py
with smtplib.SMTP('localhost', port) as server:
...
......@@ -84,21 +84,21 @@ with smtplib.SMTP('localhost', port) as server:
`SMTP`类管理与 SMTP 服务器的连接。
```
```py
# server.login('username', 'password')
```
由于我们使用本地开发服务器,因此不必登录。
```
```py
server.sendmail(sender, receivers, msg.as_string())
```
电子邮件带有`sendmail()`发送。
```
```py
$ python -m smtpd -c DebuggingServer -n localhost:1025
---------- MESSAGE FOLLOWS ----------
b'Content-Type: text/plain; charset="us-ascii"'
......@@ -124,7 +124,7 @@ Mailtrap 提供了一项免费计划,使我们每个月可以发送 500 封邮
`mailtrap_simple.py`
```
```py
#!/usr/bin/env python
import smtplib
......@@ -152,7 +152,7 @@ with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
该示例将简单邮件发送到 Mailtrap 帐户。
```
```py
server.login(user, password)
```
......@@ -165,7 +165,7 @@ server.login(user, password)
`words.txt`
```
```py
falcon
blue
sky
......@@ -177,7 +177,7 @@ cloud
`mailtrap_attachment.py`
```
```py
#!/usr/bin/python
import smtplib
......@@ -215,7 +215,7 @@ with smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
该示例向 Mailtrap 发送带有文本文件附件的电子邮件。
```
```py
filename = 'words.txt'
with open(filename, 'r') as f:
part = MIMEApplication(f.read(), Name=basename(filename))
......@@ -224,7 +224,7 @@ with open(filename, 'r') as f:
我们阅读了文本文件的内容。
```
```py
part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename))
msg.attach(part)
......@@ -236,7 +236,7 @@ msg.attach(part)
Mailtrap 在任何 SMTP 端口上都不支持 SSL,它仅支持 STARTTLS。 如果我们尝试使用 SSL,则会收到以下错误消息:
```
```py
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1045)
```
......@@ -245,7 +245,7 @@ ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1045)
`mailtrap_secured.py`
```
```py
#!/usr/bin/env python
import smtplib
......@@ -278,7 +278,7 @@ with smtplib.SMTP("smtp.mailtrap.io", port) as server:
该示例将电子邮件发送到具有机会性 TLS 的 Mailtrap 帐户。
```
```py
server.starttls() # Secure the connection
```
......@@ -291,7 +291,7 @@ server.starttls() # Secure the connection
`send_mail_ssl.py`
```
```py
#!/usr/bin/env python
import smtplib, ssl
......
......@@ -12,7 +12,7 @@ openpyxl 是用于读取和写入 Excel 2010 xlsx / xlsm / xltx / xltm 文件的
在本教程中,我们使用 xlsx 文件。 xlsx 是 Microsoft Excel 使用的开放 XML 电子表格文件格式的文件扩展名。 xlsm 文件支持宏。 xlsx 是专有的二进制格式,而 xlsx 是基于 Office Open XML 格式的。
```
```py
$ sudo pip3 install openpyxl
```
......@@ -25,7 +25,7 @@ $ sudo pip3 install openpyxl
`write_xlsx.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -46,28 +46,28 @@ book.save("sample.xlsx")
在示例中,我们创建一个新的 xlsx 文件。 我们将数据写入三个单元格。
```
```py
from openpyxl import Workbook
```
`openpyxl`模块,我们导入`Workbook`类。 工作簿是文档所有其他部分的容器。
```
```py
book = Workbook()
```
我们创建一个新的工作簿。 始终使用至少一个工作表创建一个工作簿。
```
```py
sheet = book.active
```
我们获得对活动工作表的引用。
```
```py
sheet['A1'] = 56
sheet['A2'] = 43
......@@ -75,7 +75,7 @@ sheet['A2'] = 43
我们将数值数据写入单元格 A1 和 A2。
```
```py
now = time.strftime("%x")
sheet['A3'] = now
......@@ -83,7 +83,7 @@ sheet['A3'] = now
我们将当前日期写入单元格 A3。
```
```py
book.save("sample.xlsx")
```
......@@ -100,7 +100,7 @@ Figure: New file
`write2cell.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -117,14 +117,14 @@ book.save('write2cell.xlsx')
在示例中,我们将两个值写入两个单元格。
```
```py
sheet['A1'] = 1
```
在这里,我们将数值分配给 A1 单元。
```
```py
sheet.cell(row=2, column=2).value = 2
```
......@@ -137,7 +137,7 @@ sheet.cell(row=2, column=2).value = 2
`appending_values.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -163,7 +163,7 @@ book.save('appending.xlsx')
在示例中,我们将三列数据附加到当前工作表中。
```
```py
rows = (
(88, 46, 57),
(89, 38, 12),
......@@ -177,7 +177,7 @@ rows = (
数据存储在元组的元组中。
```
```py
for row in rows:
sheet.append(row)
......@@ -191,7 +191,7 @@ for row in rows:
`read_cells.py`
```
```py
#!/usr/bin/env python
import openpyxl
......@@ -212,14 +212,14 @@ print(a3.value)
该示例加载一个现有的 xlsx 文件并读取三个单元格。
```
```py
book = openpyxl.load_workbook('sample.xlsx')
```
使用`load_workbook()`方法打开文件。
```
```py
a1 = sheet['A1']
a2 = sheet['A2']
a3 = sheet.cell(row=3, column=1)
......@@ -228,7 +228,7 @@ a3 = sheet.cell(row=3, column=1)
我们读取 A1,A2 和 A3 单元的内容。 在第三行中,我们使用`cell()`方法获取 A3 单元格的值。
```
```py
$ ./read_cells.py
56
43
......@@ -250,7 +250,7 @@ Figure: Items
`read_cells2.py`
```
```py
#!/usr/bin/env python
import openpyxl
......@@ -268,14 +268,14 @@ for c1, c2 in cells:
在示例中,我们使用范围运算从两列读取数据。
```
```py
cells = sheet['A1': 'B6']
```
在这一行中,我们从单元格 A1-B6 中读取数据。
```
```py
for c1, c2 in cells:
print("{0:8} {1:8}".format(c1.value, c2.value))
......@@ -283,7 +283,7 @@ for c1, c2 in cells:
`format()`功能用于在控制台上整洁地输出数据。
```
```py
$ ./read_cells2.py
Items Quantity
coins 23
......@@ -302,7 +302,7 @@ books 30
`iterating_by_rows.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -333,14 +333,14 @@ book.save('iterbyrows.xlsx')
该示例逐行遍历数据。
```
```py
for row in sheet.iter_rows(min_row=1, min_col=1, max_row=6, max_col=3):
```
我们提供了迭代的边界。
```
```py
$ ./iterating_by_rows.py
88 46 57
89 38 12
......@@ -359,7 +359,7 @@ $ ./iterating_by_rows.py
`iterating_by_columns.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -390,7 +390,7 @@ book.save('iterbycols.xlsx')
该示例逐列遍历数据。
```
```py
$ ./iterating_by_columns.py
88 89 23 56 24 34
46 38 59 21 18 15
......@@ -406,7 +406,7 @@ $ ./iterating_by_columns.py
`mystats.py`
```
```py
#!/usr/bin/env python
import openpyxl
......@@ -437,28 +437,28 @@ print("Variance: {0}".format(stats.variance(values)))
在示例中,我们从工作表中读取所有值并计算一些基本统计信息。
```
```py
import statistics as stats
```
导入`statistics`模块以提供一些统计功能,例如中值和方差。
```
```py
book = openpyxl.load_workbook('numbers.xlsx', data_only=True)
```
使用`data_only`选项,我们从单元格而不是公式中获取值。
```
```py
rows = sheet.rows
```
我们得到所有不为空的单元格行。
```
```py
for row in rows:
for cell in row:
values.append(cell.value)
......@@ -467,7 +467,7 @@ for row in rows:
在两个 for 循环中,我们从单元格中形成一个整数值列表。
```
```py
print("Number of values: {0}".format(len(values)))
print("Sum of values: {0}".format(sum(values)))
print("Minimum value: {0}".format(min(values)))
......@@ -481,7 +481,7 @@ print("Variance: {0}".format(stats.variance(values)))
我们计算并打印有关值的数学统计信息。 一些功能是内置的,其他功能是通过`statistics`模块导入的。
```
```py
$ ./mystats.py
Number of values: 312
Sum of values: 15877
......@@ -504,7 +504,7 @@ Variance: 809.9262820512821
`filter_sort.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -542,7 +542,7 @@ wb.save('filtered.xlsx')
`dimensions.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -580,7 +580,7 @@ book.save('dimensions.xlsx')
该示例计算两列数据的维数。
```
```py
sheet['A3'] = 39
sheet['B3'] = 19
......@@ -600,14 +600,14 @@ for row in rows:
我们将数据添加到工作表。 请注意,我们从第三行开始添加。
```
```py
print(sheet.dimensions)
```
`dimensions`属性返回非空单元格区域的左上角和右下角单元格。
```
```py
print("Minimum row: {0}".format(sheet.min_row))
print("Maximum row: {0}".format(sheet.max_row))
......@@ -615,7 +615,7 @@ print("Maximum row: {0}".format(sheet.max_row))
使用`min_row``max_row`属性,我们可以获得包含数据的最小和最大行。
```
```py
print("Minimum column: {0}".format(sheet.min_column))
print("Maximum column: {0}".format(sheet.max_column))
......@@ -623,7 +623,7 @@ print("Maximum column: {0}".format(sheet.max_column))
通过`min_column``max_column`属性,我们获得了包含数据的最小和最大列。
```
```py
for c1, c2 in sheet[sheet.dimensions]:
print(c1.value, c2.value)
......@@ -631,7 +631,7 @@ for c1, c2 in sheet[sheet.dimensions]:
我们遍历数据并将其打印到控制台。
```
```py
$ ./dimensions.py
A3:B9
Minimum row: 3
......@@ -662,7 +662,7 @@ Figure: Sheets
`sheets.py`
```
```py
#!/usr/bin/env python
import openpyxl
......@@ -681,14 +681,14 @@ print(sheet.title)
该程序可用于 Excel 工作表。
```
```py
print(book.get_sheet_names())
```
`get_sheet_names()`方法返回工作簿中可用工作表的名称。
```
```py
active_sheet = book.active
print(type(active_sheet))
......@@ -696,21 +696,21 @@ print(type(active_sheet))
我们获取活动表并将其类型打印到终端。
```
```py
sheet = book.get_sheet_by_name("March")
```
我们使用`get_sheet_by_name()`方法获得对工作表的引用。
```
```py
print(sheet.title)
```
检索到的工作表的标题将打印到终端。
```
```py
$ ./sheets.py
['January', 'February', 'March']
<class 'openpyxl.worksheet.worksheet.Worksheet'>
......@@ -722,7 +722,7 @@ March
`sheets2.py`
```
```py
#!/usr/bin/env python
import openpyxl
......@@ -747,35 +747,35 @@ book.save('sheets2.xlsx')
在此示例中,我们创建一个新工作表。
```
```py
book.create_sheet("April")
```
使用`create_sheet()`方法创建一个新图纸。
```
```py
print(book.sheetnames)
```
图纸名称也可以使用`sheetnames`属性显示。
```
```py
book.remove_sheet(sheet1)
```
可以使用`remove_sheet()`方法将纸张取出。
```
```py
book.create_sheet("January", 0)
```
可以在指定位置创建一个新图纸。 在我们的例子中,我们在索引为 0 的位置创建一个新工作表。
```
```py
$ ./sheets2.py
['January', 'February', 'March', 'April']
['February', 'March', 'April']
......@@ -789,7 +789,7 @@ $ ./sheets2.py
`sheets3.py`
```
```py
#!/usr/bin/env python
import openpyxl
......@@ -805,7 +805,7 @@ book.save('sheets3.xlsx')
该示例修改了标题为“ March”的工作表的背景颜色。
```
```py
sheet.sheet_properties.tabColor = "0072BA"
```
......@@ -824,7 +824,7 @@ Figure: Background colour of a worksheet
`merging_cells.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -845,28 +845,28 @@ book.save('merging.xlsx')
在该示例中,我们合并了四个单元格:A1,B1,A2 和 B2。 最后一个单元格中的文本居中。
```
```py
from openpyxl.styles import Alignment
```
为了使文本在最后一个单元格中居中,我们使用了`openpyxl.styles`模块中的`Alignment`类。
```
```py
sheet.merge_cells('A1:B2')
```
我们用`merge_cells()`方法合并四个单元格。
```
```py
cell = sheet.cell(row=1, column=1)
```
我们得到了最后一个单元格。
```
```py
cell.value = 'Sunny day'
cell.alignment = Alignment(horizontal='center', vertical='center')
......@@ -884,7 +884,7 @@ Figure: Merged cells
`freezing.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -901,7 +901,7 @@ book.save('freezing.xlsx')
该示例通过单元格 B2 冻结窗格。
```
```py
sheet.freeze_panes = 'B2'
```
......@@ -914,7 +914,7 @@ sheet.freeze_panes = 'B2'
`formulas.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -944,7 +944,7 @@ book.save('formulas.xlsx')
在示例中,我们使用`SUM()`函数计算所有值的总和,并以粗体显示输出样式。
```
```py
rows = (
(34, 26),
(88, 36),
......@@ -961,21 +961,21 @@ for row in rows:
我们创建两列数据。
```
```py
cell = sheet.cell(row=7, column=2)
```
我们得到显示计算结果的单元格。
```
```py
cell.value = "=SUM(A1:B6)"
```
我们将一个公式写入单元格。
```
```py
cell.font = cell.font.copy(bold=True)
```
......@@ -992,7 +992,7 @@ Figure: Calculating the sum of values
`write_image.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -1012,21 +1012,21 @@ book.save("sheet_image.xlsx")
在示例中,我们将图像写到一张纸上。
```
```py
from openpyxl.drawing.image import Image
```
我们使用`openpyxl.drawing.image`模块中的`Image`类。
```
```py
img = Image("icesid.png")
```
创建一个新的`Image`类。 `icesid.png`图像位于当前工作目录中。
```
```py
sheet.add_image(img, 'B2')
```
......@@ -1041,7 +1041,7 @@ sheet.add_image(img, 'B2')
`create_bar_chart.py`
```
```py
#!/usr/bin/env python
from openpyxl import Workbook
......@@ -1086,7 +1086,7 @@ book.save("bar_chart.xlsx")
在此示例中,我们创建了一个条形图,以显示 2012 年伦敦每个国家/地区的奥运金牌数量。
```
```py
from openpyxl.chart import (
Reference,
Series,
......@@ -1097,7 +1097,7 @@ from openpyxl.chart import (
`openpyxl.chart`模块具有使用图表的工具。
```
```py
book = Workbook()
sheet = book.active
......@@ -1105,7 +1105,7 @@ sheet = book.active
创建一个新的工作簿。
```
```py
rows = [
("USA", 46),
("China", 38),
......@@ -1122,21 +1122,21 @@ for row in rows:
我们创建一些数据并将其添加到活动工作表的单元格中。
```
```py
data = Reference(sheet, min_col=2, min_row=1, max_col=2, max_row=6)
```
对于`Reference`类,我们引用表中代表数据的行。 在我们的案例中,这些是奥运金牌的数量。
```
```py
categs = Reference(sheet, min_col=1, min_row=1, max_row=6)
```
我们创建一个类别轴。 类别轴是将数据视为一系列非数字文本标签的轴。 在我们的案例中,我们有代表国家名称的文本标签。
```
```py
chart = BarChart()
chart.add_data(data=data)
chart.set_categories(categs)
......@@ -1145,7 +1145,7 @@ chart.set_categories(categs)
我们创建一个条形图并为其设置数据和类别。
```
```py
chart.legend = None
chart.y_axis.majorGridlines = None
......@@ -1153,21 +1153,21 @@ chart.y_axis.majorGridlines = None
使用`legend``majorGridlines`属性,可以关闭图例和主要网格线。
```
```py
chart.varyColors = True
```
`varyColors`设置为`True`,每个条形都有不同的颜色。
```
```py
chart.title = "Olympic Gold medals in London"
```
为图表设置标题。
```
```py
sheet.add_chart(chart, "A8")
```
......
此差异已折叠。
......@@ -16,7 +16,7 @@ YAML 本机支持三种基本数据类型:标量(例如字符串,整数和
PyYAML 是 Python 的 YAML 解析器和发射器。
```
```py
$ pip install pyyaml
```
......@@ -29,7 +29,7 @@ $ pip install pyyaml
`items.yaml`
```
```py
raincoat: 1
coins: 5
books: 23
......@@ -43,7 +43,7 @@ pens: 6
`data.yaml`
```
```py
cities:
- Bratislava
- Kosice
......@@ -67,7 +67,7 @@ companies:
`read_yaml.py`
```
```py
#!/usr/bin/env python3
import yaml
......@@ -81,7 +81,7 @@ with open('items.yaml') as f:
我们打开`items.yaml`文件,并使用`yaml.load()`方法加载内容。 数据被打印到控制台。
```
```py
$ python read_yaml.py
{'raincoat': 1, 'coins': 5, 'books': 23, 'spectacles': 2, 'chairs': 12, 'pens': 6}
......@@ -95,7 +95,7 @@ PyYAML 模块将标量值转换为 Python 字典。
`read_docs.py`
```
```py
#!/usr/bin/env python3
import yaml
......@@ -113,7 +113,7 @@ with open('data.yaml') as f:
该示例从`data.yaml`文件中读取两个文档。
```
```py
$ python read_docs.py
cities -> ['Bratislava', 'Kosice', 'Trnava', 'Moldava', 'Trencin']
companies -> ['Eset', 'Slovnaft', 'Duslo Sala', 'Matador Puchov']
......@@ -128,7 +128,7 @@ companies -> ['Eset', 'Slovnaft', 'Duslo Sala', 'Matador Puchov']
`dumping.py`
```
```py
#!/usr/bin/env python3
import yaml
......@@ -142,7 +142,7 @@ print(yaml.dump(users))
在示例中,我们有一个词典列表。 我们使用`dump()`方法将列表序列化为 YAML 格式。
```
```py
$ python dumping.py
- name: John Doe
occupation: gardener
......@@ -159,7 +159,7 @@ $ python dumping.py
`writing.py`
```
```py
#!/usr/bin/env python3
import yaml
......@@ -175,7 +175,7 @@ with open('users.yaml', 'w') as f:
该示例将词典列表写入`users.yaml`文件。
```
```py
data = yaml.dump(users, f)
```
......@@ -188,7 +188,7 @@ data = yaml.dump(users, f)
`sort_keys.py`
```
```py
#!/usr/bin/env python3
import yaml
......@@ -205,7 +205,7 @@ with open('items.yaml') as f:
该示例从`items.yaml`文件中读取数据,并通过 YAML 输出中的键对数据进行排序。
```
```py
$ python sort_keys.py
{'raincoat': 1, 'coins': 5, 'books': 23, 'spectacles': 2, 'chairs': 12, 'pens': 6}
books: 23
......@@ -225,7 +225,7 @@ spectacles: 2
`tokens.py`
```
```py
#!/usr/bin/env python3
import yaml
......@@ -241,7 +241,7 @@ with open('items.yaml') as f:
该示例扫描 YAML 文件并打印记号。
```
```py
$ python tokens.py
StreamStartToken(encoding=None)
BlockMappingStartToken()
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -14,7 +14,7 @@ Python 列表具有`reverse()`函数。 `[::-1]` slice 操作可反转 Python
`reverse_list.py`
```
```py
#!/usr/bin/env python3
nums = [2, 7, 8, 9, 1, 0]
......@@ -29,7 +29,7 @@ print(rev_nums)
`reverse()`方法在适当的位置反转列表。 `nums[::-1]`创建一个列表的新副本,其中元素被反转。
```
```py
$ ./reverse_list.py
[0, 1, 9, 8, 7, 2]
......@@ -43,7 +43,7 @@ $ ./reverse_list.py
`reversed_fun.py`
```
```py
#!/usr/bin/env python3
words = ['forest', 'wood', 'sky', 'rock']
......@@ -65,7 +65,7 @@ for e in reversed(range(1, 10, 2)):
在示例中,我们在列表,单词和范围上使用`reversed()`函数。
```
```py
$ ./reversed_fun.py
rock
sky
......@@ -88,7 +88,7 @@ t s e r o f
`custom_string_reverse.py`
```
```py
#!/usr/bin/env python3
def reverse_string(word):
......@@ -109,7 +109,7 @@ print(reverse_string('forest'))
请注意,这只是出于演示目的; 这个实现很慢。
```
```py
def reverse_string(word):
rev = ''
......@@ -130,7 +130,7 @@ def reverse_string(word):
`reversed_magic.py`
```
```py
#!/usr/bin/env python3
class Vowels(object):
......@@ -167,7 +167,7 @@ print()
在示例中,我们在`Vowels`对象中实现`__reversed__()`方法。
```
```py
$ ./reversed_magic.py
normal order:
a e i o u y
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册