Professional Documents
Culture Documents
Python
Python
:
TasPython
2008 / & ,
, . ,
,
,
.
, ,
, , ,
.
,
,
.
TasPython , , .
,
.
iii
iv
vi
1.1 . . . . . . . . . . . . . . . . . . . . .
1.2
. . . . . . . . . . . . . . . . .
1.2.1 . . . . . . . . . . .
1.2.2 . . . . . .
1.2.3 . . . . . . . . . . . . . . . . . . . . . .
1.2.4 . . . . . . . . . . . . .
1.2.5 . . . . . . . . . . . . . . . . . . . . .
1.2.6 . . . . . . . . . . . . . . . . . . . .
1.2.7 . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.8 . . . . . . . . . . . . . .
1.3 Python . . . . . . . . . . . . . . . . . . . . . . . . .
1.3.1 . . . . . . . . . . . . . . . . . . .
1.3.2 Python 3 . . . . . . . . . . . . . . . . . . . . . . . . . .
10
1.3.3 . . . . . . . . . . . . . . . . . . . . . . . . .
12
1.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . .
12
13
1.4 Python . . . . . . . . . . . . . . . . . . . . . . . .
14
1.4.1 . . . . . . . . . . . . . . . . . . . . . . .
14
1.4.2 Python . . . . . . . . . .
15
1.5 . . . . . . . . . . . . . . . . . . . . . . . .
18
vii
viii
2
21
2.1 . . . . . . . . . . . . . . . . . . . . . . . . . .
22
2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . .
23
2.3 Boolean . . . . . . . . . . . . . . . . . . . . . . . .
24
2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
26
29
3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29
3.2
. . . . . . . . . . . . . . . . . . . . .
30
3.3 . . . . . . . . . . . . . . . . . . . . . . . .
31
3.4 if
. . . . . . . . . . . . . . . . . . . . . . . . .
32
3.4.1 . . . . . . . . . . . . . . . . . .
34
3.5 . . . . . . . . . . . . . . . . . . . . . . .
36
3.5.1 for . . . . . . . . . . . . . . . . . . . . . . . .
36
3.5.2 while . . . . . . . . . . . . . . . . . . . . . . .
38
3.6 break . . . . . . . . . . . . . . . . . . . . . . . . .
38
3.7 with . . . . . . . . . . . . . . . . . . . . . . . . . .
39
3.7.1 with . . . . . . . . . . . . . . . . . . . . . .
40
3.7.2 . . . . . . . . . . . . . . . . . . . . . . .
41
4
4.1
43
. . . . . . . . . . . . . . . . . . . . . . . . .
44
4.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . .
44
4.1.2
. . . . . . . . . . . . . . . . . . . .
44
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
45
4.2
4.3
. . . . . . . . . . . . . . . . .
46
4.4 . . . . . . . . . . . . . . . . . . . . . . . .
47
5
5.1
49
. . . . . . . . . . . . . . . . . . . . . . . . .
50
5.2 . . . . . . .
51
5.3 (Docstrings) . . . . . . . . . . . .
52
5.4 . . . . . . . . . . . . . . . . . . . . .
54
5.4.1 . . . . . . . . . . . . . . . . . . . . . .
54
5.5 . . . . . . . . . . . . . . . . . . . . . .
55
ix
5.6 (Decorators) . . . . . . . . . . . . . . . . . . . .
6
59
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . .
6.1.1
56
60
. . . . . . . . . . . . . . . . .
60
6.2 . . . . . . . . . . . . . . . . . . . . . . . . . .
61
6.2.1 . . . . . . . . . . . . .
61
6.2.2 . . . . . . . . . . . . . . .
62
6.2.3 . . . . . . . . . . . . . .
63
6.2.4 . . . . . . . . . . . . . . .
64
6.2.5 . . . . . . . . . . . . . . . . . . .
64
6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
66
6.3.1 . . . . . . . . . . . . . . . . . . . . .
67
6.3.2 . . . . . . . . . . . . . . .
68
6.3.3 . . . . . . . . . . . . . . . . .
70
6.3.4 . . . . . . . . . . . . . . . . . . . .
70
71
6.3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . .
72
6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
72
6.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
73
6.5.1 . . . . . . . . . . . . . . . . . . . .
73
6.5.2 . . . . . . . . . . . . . . . . . . .
74
6.5.3 . . . . . . . . . . . . . . . . . . . . . . .
76
6.5.4 . . . . . . . . . . . . . . . .
76
77
6.5.6 . . . . . . . . . . . . . . . . . . .
77
6.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
78
6.6.1 . . . . . . . . . . . . . . . . . . . . . . . .
78
6.6.2 . . . . . . . . . . . . . . . . .
79
7
7.1 (immutable objects)
81
. . . . . . . . . . . . . . . .
81
7.2 . . . . . . . . . . . . . . . .
83
7.3 . . . . . . . . . . . . . . . . . . . . . . .
86
7.3.1 . . . . . . . . . . . . . . . . . . . . . . . .
87
7.3.2 None . . . . . . . . . . . . . . . . . . . . . . . . . . . .
87
7.4 . . . . . . . . . . . . . . . . . . . . . . . . .
88
7.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
90
7.6 . . . . . . . . . . . . . . . . . . . . .
94
99
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
99
8.2 . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.3 . . . . . . . . . . . . . . . . . 104
8.4 (attributes) . . . . . . . . . . . . . . 107
8.5 . . . . . . . . . . . . . . . . . . . . . . . 108
8.6 . . . . . . . . . . . . 109
8.6.1 . . . . . . . . . . . . . . . . . . . . 109
8.6.2 . . . . . . . . . . . . . . . . . . . . . 110
8.7 . . . . . . . . . . . . . . . . . . . . . . . . . 110
8.8 . . . . . . . . . . . . . . . . . . . . . . . . . 112
9
115
9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
9.2 . . . . . . . . . . . . . . . . . . . . . . . 116
9.2.1 . . . . . . . . . . . . . . . . . . . 116
9.2.2 . . . . . . . . . . . . . . . . . . . . 117
9.2.3
. . . . . . . . . . . . . . . . . . . . 117
9.2.4 () . . . . . 118
9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.3.1
. . . . . . . . . . . . . . . . . 119
9.3.2 . . . . . . . . . . . . . . . . . . . 122
10
123
10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 124
10.3 . . . . . . . . . . . . . . . . . . . . . 128
10.4
. . . . . . . . . . . . . . . . . . . . . . . . . . . 129
xi
10.5
. . . . . . . . . . . . . . . . . . . . . 131
10.5.1 . . . . . . . . . . . . . . . . . . . 131
10.5.2 (raise) . . . . . . . . . . . . . . . 132
10.5.3 . . . . . . . . . 132
10.6 if . . . else . . . . . . . . . . . . . . . . . . . . . . 133
11
139
. . . . . . . . . . . . . . . . . . . . . 140
11.3
. . . . . . . . 143
11.4 . . . . . . . . 144
12
12.1
147
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
13
149
13.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
13.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
13.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 150
14 GUI tkinter
153
14.1 . . . . . . . . . . . . . . . . . . . . . . . . . 154
14.2 . . . . . . . . . . . . . . . . . . . 154
14.3 . . . . . . . . . . . . . . . . 160
15
163
15.1 . . . . . . . . . . . . . . . . . . . . . . . . . 163
15.1.1 . . . . . . . . . . . . . . . . . . . 163
15.1.2 . . . . . . . . . . . . . . . 164
15.1.3 . . . . . . . . . . . . . . . . . . . . . 164
15.2 Python Debugger . . . . . . . . . . . . . . . . . . . . . . . . . 164
15.2.1 . . . . . . . . . . . . . . . . . . . . 165
15.2.2 . . . . . . . . . . . . . . . . . . . . . . . . 165
15.2.3 . . . . . . . . . . . . . . . . . 166
15.2.4 . . . . . . . . . . . . . . . . . . . . 166
xii
16
169
16.1 . . . . . . . . . . . . . 170
16.2 . . . . . . . . . . . . 171
16.3 garbage collector . . . . . . . . . . . . . . . . . 173
16.4 . . . . . . . . . . . . . . . 173
16.5 . . . . . . . . . . . . . . . . . . . . 175
16.6 (Profiling)
. . . . . . . . . . . . . . . . . . 175
Python 3. . -
.
, . :
,
.
, .
, .
1
1.
1.1
, , . .
, .
.
,
,
.
1. .
2. .
p r i n t ( ' Hello , World ! ' )
3. _..
4. , _..
,
. ,
, .
1.2
Python
.
Linux
web applications (
Django). ,
1.2.
,
.
.
1.2.1
,
.
. , (compile)1
, ,
.
,
,
,
.
.
. .
1.2.2
, , , . , .
,
.
,
, 1
1.
. ,
( ),
,
.
, ,
.
,
. ,
,
.
1.2.3
,
. !,
.
, .
,
. ,
. ,
.
. ,
!
, ,
. , ,
. ,
!
, !
1.2.
1.2.4
. ,
.
.
.
.
1.2.5
, , . .
. .
, Python .
. , ,
.
.
1.2.6
.
.
,
.
,
.
1.
1.2.7
(compiler) . .
.
,
.
,
.
, . ,
. , ,
.
1.2.8
.
. , ,
. Python
. ,
. (bugs),
.
1.3
Python
Python ,
(semantics).
(standard library).
:
1.3. Python
( , )
segmentation faults
Python .
,
.
.
, . ,
- ,
.
Python
( C, C++)
1.
Python 3 5 Java. ,
.
( ) .
.
(efficiency),
(productivity).
, . (interpreters)
(compilers).
.
(virtual machine) (
Python). ,
, (bytecode).
(object code).
.
,
.
, .
, (modules)
,
,
( 3 Python
1.3. Python
).
, ( Windows, Linux/Unix, OS/2, Mac, Amiga). , Java, Jython Java, .NET
IronPython Microsoft. , C/C++ (modules)
Python.
, . 1980
. ,
.
, ,
Python segmentation faults. ,
Python (
throw)
.
. , Python
.
(reference counting).
1.3.1
Python, .
(generators), , .
,
,
( , ..).
1.
10
, , , , ( )
. Python
, .
, ,
, ,
.
.
(Python Enhancement Proposal (PEP))
(
PEP 8 PEP 257)
1.3.2 Python 3
Python ,
1980.
,
(
2 import this)
. :
7 / 4 = 1 C.
range ( )
2
Linux python3
, Windows IDLE.
1.3. Python
11
print statement
.
Unicode ( ) .
... .
,
. Python 3 ( py3k 3000).
,
.
:
7 / 4 = 1.75 ( // )
. range
3
.
print
Unicode, .
...
Python.
3
11.2.
1.
12
1.3.3
2
:
2to3
3to2
python -3
2
3 , . Python (2.6+)
3 Python.
, PEP 3003 (Python Enhancement Proposal) 2
Python (CPython)
( Jython, Pypy, IronPython)
.
1.3.4
Python,
:
1.3. Python
13
Python, :
1. (prototyping)
2.
3. Scripting
4.
5.
6.
7. ... !
,
. Python
.
1.
14
.
.
.
, .
.
.
.
.
, .
, .
(namespaces)
!
1.4
1.4.1
Python
Python
. ,
(
). .
Linux
Linux package manager , ( ). ,
, ,
. ,
Python 3. .
1.4. Python
15
,
. , ,
( IDLE).
Mac, Python . , , .
. , Applications / Utilities / Terminal Python.
, , 3 .
1.4.2
Python
Python .py.
.
.py .
:
>>> a = 5
>>> b = 6
>>> a + b
11
(interpreter), (
Linux, > > cmd Windows) python ( python3 ).
>>> ,
.
1.
16
Windows
python.
1. Python PATH. ,
-> -> ->
(Control Panel -> System -> Advanced ->
Environment Variables) (path) Python. (command line) python onoma.py.
2. IDLE ( python ).
(File > Open). , Run Module
> Run .
Notepad Wordpad. , Notepad++ .
Linux
1. path
. python3 onoma.py
4 .
2. ,
#! / usr/bin/env python3
python 3 python3
/usr/bin
1.4. Python
17
#!/ usr/bin/python3
. #/usr/bin/env python3
Python 3
( /usr/bin/python3) . ,
. , ,
.
PEP5 8
Python, tab ,
(indent) .6
"Unknown option: -",
. Unix .
.
1. Notepad++
Tabs: Settings > Preferences > Edit Components > Tab settings.
Settings > Preferences > MISC > auto-indent.
: Format > Convert, Unix.
2. JEdit
: U W M , U
5
PEP: Python Enhancement Proposal. , ,
..
6
PEPs
http://python.org/dev/peps/.
1.
18
3. Mac TextWrangler
Tabs:
Auto Expand Tabs. Defaults > Auto-Expand Tabs Defaults >
Auto-indent.
: , Unix.
. Windows, IDLE (
) , Eclipse
pydev. Linux kate gedit,
Eclipse.
( ).
,
.
1.5
:
1
Python.
2 .
,
.
3 , .
4 .
5
.
1.5.
19
6 :
.
7 Python
.
8 : .
.
9
. ,
.
10
.
11
Python, .
13
.
14
(tkinter)
Python.
15 .
, 16
( ).
20
1.
, , ,
: .
,
. ,
.
. ,
, . ,
. ,
Structure and Interpretation of Computer Programs :
1. , .
21
2.
22
2. .
3. .
.
2.1
, . , Python .
2.1.1. bit . bits
.
2.1.2.
.
.
print . ,
. ,
. , ,
, .
print ( 1 )
p r i n t ( ' asdf ' )
primeNumbers = 1 , 2 , 3 , 5 , 7
p r i n t ( primeNumbers )
Python .
,
2.2.
23
, .
dynamic typing. ,
Python
.
. :
a = ' asdf '
a = 2
a = pow ( a , 100000)
print ( a )
a
.
2.1.3. (dynamically
typed),
.
,
. , Python
.
2.2
2.2.1. .
. , .
num = 17
pi = 3.14
paei = ' Allou '
paei = ' Molis g y r i s e '
2.
24
. , ,
. , . , ,
.
, . pi
3.14 .
pi = 3.14
p r i n t ( pi 2)
2.3
Boolean
2.3.1. Boolean
.
5 == 5 ()
5 == 6 ()
True and False ()
True or False ()
Boolean .
.
Boolean :
not
or
and
2.3. Boolean
25
2.1: not
2.2: and
2.3: or
(
and), ( or) ( not
and)1 . .
1
De Morgan
.
2.
26
>>> a = 5
>>> b = 4
>>> a > b
True
>>> c = 6
>>> a > b and a > c
False
>>> a > b or a > c
True
>>> a > b and not a > c
True
>>> a > b or not a > c
True
>>> not a > b or not a > c
True
>>> not ( a > b ) or a > c
False
>>> not a > b or a > c
False
2.4
Boolean (
) .
2.4.1. .
.
,
5.
:
2.4.
27
(+)
()
()
(/)
()
(modulo) (%)
. . Python
.
(==)
(! =)
(>)
(<)
(>=)
(<=)
28
2.
It is not enough to do your best; you must
know what to do, and then do your best.
W. Edwards Deming
3.1
.
.
3.1.1. ( ).
.
:
: .
:
( , , ).
: .
29
3.
30
! Python !
:
IndentationError : expected an indented block
.
tabs
.
tabs .
, PEP
8 .
. ,
.
,
. , Python
.
3.2
3.2.1.
, .
, ,
. .
. .
sequential, .
:
p r i n t (123)
3.3.
31
print ( )
print ( ' Hello ' , end= ' ' )
print ( ' World ' )
print() , , .
end
.
,
(program counter).
.
3.3
3.3.1. :
(, ).
,
.
3.
32
3.4
if
, if
.
, if ,
if.
answer = i n t ( input ( ' What i s the product o f 2 5: ' ) )
i f ( answer == 1 0 ) :
p r i n t ( ' Correct ! ' )
p r i n t ( ' Exiting program ' )
, .
:
What i s the product o f 2 5: g
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
ValueError : i n v a l i d l i t e r a l for i n t ( ) with base 10: ' g '
g
int(), ,
ValueError.
.
.
,
if...else....
from math import sqrt
3.4. if
33
.
.
: x1,2 =
+
, = 2 4 . 2
(
if 1 ( else).
0 ,
.
3.
34
3.4.1
if...elif...else...
Python, switch k , k
switch.
switch C/C++ Java. Python, if...elif...else....
:
x = i n t ( input ( " Please enter an i n t e g e r : " ) )
i f x < 0:
p r i n t ( ' Negative number, transforming i n t o p o s i t i v e ' )
x = x # make i t p o s i t i v e
# Be careful , because the f o l l o w i n g statements w i l l be
# examined only i f the f i r s t condition i s f a l s e , they
# won ' t be executed
e l i f x == 0:
p r i n t ( ' Zero ' )
e l i f x == 1:
p r i n t ( ' One ' )
else :
p r i n t ( ' Great than 1 ' )
, elif
, .
switch,
.
Python
.
(key)
. -
3.4. if
35
,
, .
# Sample functions
def square ( x ) :
return x 2
def double ( x ) :
return x 2
opdict = { " a " : square , " b " : square , " c " : double }
# Example ( random access O( 1 ) )
print ( opdict [ " b " ] ( 5 ) )
# Example 2 ( checking everything )
for operation in " abc " :
prin t ( operation , opdict [ operation ] ( 3 ) )
if...elif...else....
, ,
.
, ,
.
# Sample functions
def square ( x ) :
return x 2
def double ( x ) :
return x 2
def decrease ( x ) :
return x1
3.
36
opdict = { " a " : square , " b " : double , " c " : decrease }
try :
p r i n t ( opdict [ " d " ] ( 5 ) )
except KeyError :
p r i n t ( ' I n v a l i d use o f index ' )
3.5
,
.
( )
, . ,
for while .
3.5.1
for
for . range(). ,
range() , .
20 Fibonacci. n-
Fibonacci Fn = Fn1 + Fn2 F0 = 0 F1 = 1.
# the 2 f i r s t f i b o n a c c i numbers are always known
a, b = 0, 1
# p r i n t the f i r s t f i b o n a c c i number ( a )
p r i n t ( a , end= ' ' )
3.5.
37
i 0 17,
18 . 2
range() .
range() ,
.
>>> for i in range (100 , 120):
...
...
100 101 102 103 104 105 106 107 108 109 110
111 112 113 114 115 116 117 118 119
...
100 102 104 106 108 110 112 114 116 118
, .
3.
38
3.5.2
while
for, while
.
def f i b ( a , b ) :
sum = 0;
while a < 4 (10 6 ) :
sum += a
a, b = b, a + b
return sum
a, b = 0, 1
print ( f i b ( a , b ) )
Fibonnaci 4 106 .
3.6
break
break .
, if
.
break
.
. ,
.
Zn (modulo).
0,
.
def printSubgroups ( n ) :
"""
Prints a l l the subgroups o f Zn
3.7. with
39
"""
for i in range ( 0 , n ) :
p r i n t ( ' < ' , end= ' ' )
p r i n t ( i , end= ' >: ' )
for j in range ( 1 , n + 1 ) :
num = ( i j )%n
p r i n t (num, end = ' ' )
i f (num % n ) == 0:
break
p r i n t ( ' , ' , end= ' ' )
print ( )
3.7
with
3 Python, with ,
.
.
with , with
.
, block with. with
.
filename = "CanadaSong . t x t "
data = " " " \
F i r s t come the black f l i e s ,
Then the Horse f l i e s ,
Then the Deer f l i e s ,
Then the snow f l i e s !
"""
with open ( filename , "w" ) as fout :
3.
40
fout . write ( data )
, with, filename,
.
,
. , with
.
3.7.1
with
with
, with .
.
,
.
# every l i n e containing these words won ' t be written
# at the output
exclude_class = [ ' not ' , ' negation ' ]
with open ( ' i n f i l e ' , ' r ' ) as f1 , open ( ' o u t f i l e ' , 'w ' ) as f2 :
# f o r each l i n e in the input f i l e
for l i n e in f1 . readlines ( ) :
# by d e f a u l t write a l i n e to the o u t f i l e unless
# i t doesn ' t contain one o f the excluded words
w r i t e _ t o _ f i l e = True
# f o r each word in a l i n e o f the input f i l e
for word in l i n e . s p l i t ( ) :
# i f t h i s word doesn ' t belong to closed_class
i f word . r s t r i p ( ) in exclude_class :
w r i t e _ t o _ f i l e = False
break
if write_to_file :
3.7. with
41
f2 . write ( l i n e )
3.7.2
42
3.
Python . :
(scripts). scripts.
.
Python , ,
. , .
(overflow). .
python
,
:
43
4.
44
python
4.1
(, , , ) (+, , , /)
>>> 3+8
11
>>> 38
5
>>> 38
24
>>> 3/8
0.375
4.1.1
.
( )
.
>>> 7/2
3.5
>>> 7//2
3
4.1.2
,
.
4.2.
45
>>> 210
1024
>>> 38
6561
n (mod n ),
python (modular exponentiation)
, .
,
.
,
21024 , 1024
1000 . Python
.
>>> pow( 2 , 1024, 1000)
216
4.2
,
:
1. d:
2. b: ( bin())
3. o: ( oct())
4. x: ( hex())
, .
4.
46
# value = 12
# value = 1100
# value = 0b1100
# value = 14
# value = 0o14
# value =
# value = 0xc
# value = 0b1100
# value = 0o14
# value = 0xc
4.3
,
(specifier) f .
. , +,
.
.
p r i n t ( ' x = { 0 : 5 . 3 f } ' . format (1234.567))
# x = 1234.567
# x = 1234.567000
# x = 1234.567000
# x = +1234.567000
# x = 00001234.567
print ( )
p r i n t ( ' x = { 0 : 1 . 5 e } ' . format (1234.567))
# x = 1.23457e+03
# x = 33.700%
4.4.
47
# pi = 3.142
# pi = 3.14159265
4.4
(, , ). complex. ,
.
a = complex ( 1 , 1)
b = complex ( 1 , 2)
print ( a+b )
print ( a b )
48
4.
, (
)
.
.
, ,
. -
,
. , . ,
.
Python .
, ,
. ,
, . ,
49
5.
50
,
, .
5.1
5.1.1. .
.
, .
5.1.2.
.
.
.
5.1.3.
return.
return,
.
. ,
.
def add ( a , b ) :
c = a + b
return c
p r i n t ( add ( 2 , 3 ) )
.
5.2.
51
5.2
(Pure Functions)
. ,
(modifier functions) . (side effects),
,
.
5.
52
string
a.
, (mutable),
, . ,
, count() b, reverse()
.
b = [ 'a ' , 'b ' , ' c ' , 'd ' , ]
p r i n t ( b . count ( ' a ' ) )
print ( b )
p r i n t ( b . reverse ( ) )
print ( b )
5.3
(Docstrings)
, .
,
.
Python, ,
.
def f i b o n a c c i ( n ) :
" " " Return the nth Fibonacci number counting from 0. " " "
# we should have used the closed formula f o r f i b o n a c c i
# TODO: throw an e r r o r f o r negative numbers
5.3. (Docstrings)
53
i f n <= 1:
return n
return f i b o n a c c i ( n 1) + f i b o n a c c i ( n 2)
print ( f i b o n a c c i ( 1 0 ) )
,
.
. . ,
, ()
. PEP 257,
,
.
, .
Python.
>>> help ( fibonnaci )
>>> prin t ( f i b o n a c c i . __doc__ )
.
,
__doc__
Python.
, Python
.
5.
54
5.4
.
.
,
.
def h e l l o ( message= ' Hello World ! ' ) :
p r i n t ( message )
hello ( )
h e l l o ( message= ' Hello Brave New World ! ' )
5.4.1
. .
.
, tuple .
>>> a = ( 1 , 2 , 3 , 4)
>>> def add ( a , b , c , d ) :
...
return a + b + c + d
...
>>> add ( a )
10
.
, .
,
( )
5.5.
55
.
.
b = { 'a ' :2 , ' c ' : 3 , 'd ' : 5 , 'b ' : 1 }
def p r i n t _ v a r i a b l e s ( a , b , c , d ) :
prin t ( ' a : { } ' . format ( a ) )
prin t ( ' b : { } ' . format ( b ) )
prin t ( ' c : { } ' . format ( c ) )
prin t ( ' d : { } ' . format ( d ) )
p r i n t _ v a r i a b l e s ( b )
varargs
default arguments ( ) Python.
5.5
. . , .
.
lambda
.
. , lambda def. 1 . ,
,
return. .
def double ( x ) :
return x x
1
5.
56
def p r i n t _ r e s u l t s ( f , args ) :
p r i n t ( f ( args ) )
p r i n t _ r e s u l t s ( double , 5) # prints 25
p r i n t _ r e s u l t s ( lambda x : x x , 5) # prints 25
5.6
(Decorators)
. ,
(randomized algorithm).
Python
. , .
. , , .
, . ,
.
Python
. , .
,
(decorators).
def makebold ( fn ) :
def wrapped ( ) :
return " <b> " + fn ( ) + " </b> "
5.6. (Decorators)
57
return wrapped
def message ( ) :
return " TasPython Guide "
message = makebold ( message )
print ( message ( ) )
g f . g f .
, makebold() wrapped().
wrapped() . . ,
f n wrapped()
. wrapped()
,
makebold().
message makebold(message). , Python .
, makebold(message)
message. message
, , .
makebold(), wrapped(). wrapped() makebold()
string fn . .
,
.
, .
def makebold ( fn ) :
def wrapped ( ) :
5.
58
return " <b> " + fn ( ) + " </b> "
return wrapped
@makebold
def message ( ) :
return " Python Guide "
p r i n t ( message ( ) )
, ,
message()
,
. , message(),
makebold.
.
. , ,
,
Python . ,
.
59
6.
60
6.1
6.1.1
(Lists): [ ].
. (mutable).
[ ' These ' , 3 , 5.711 , True , ' Prime ' ]
(Dictionaries): { }
. ( )
:
key: .
value: ,
.
{ 1 : ' alpha ' , 2: ' beta ' , 3: 'gamma ' , 4: ' d e l t a ' }
(Sets): ,
set .
.
6.2.
61
.
.
.
.
keys.
.
6.1:
6.2
6.2.1
, ,
.
,
.
UTF-8.
# the v a r i a b l e myString points to an immutable s t r i n g
myString = ' This i s a s t r i n g . '
(sequence).
,
.
6.
62
'. '
6.2.2
,
. ,
.
def reverse ( t e x t ) :
return t e x t [ : : 1 ]
6.2.
63
6.2.3
string.format(). python, strings .
,
{x}, x
.
s f = ' the { } jumped over the { } ! '
print ( s f . format ( ' mouse ' , ' moon ' ) )
6.
64
6.2.4
repr() ,
.
rjust() string, , .
for x in range ( 1 , 1 1 ) :
p r i n t ( repr ( x ) . r j u s t ( 2 ) , repr ( x x ) . r j u s t ( 3 ) , \
repr ( x x x ) . r j u s t ( 4 ) )
, ,
, format().
for x in range ( 1 , 1 1 ) :
p r i n t ( ' { 0 : 2 d } { 1 : 3 d } { 2 : 4 d } ' . format ( x , x x , x x x ) )
split().
>>> a = ' asdf '
>>> b = ' asdasdfnbfds '
>>> a . s p l i t ( '' )
[ ' asdf ' ]
>>> b . s p l i t ( '' )
[ ' asdasdf ' , ' nbfds ' ]
split()
.
,
, .
6.2.5
6.2.
65
6.
66
p r i n t ( " Lines
: " , lines )
: " , sentences )
p r i n t ( "Words
: " , words )
6.3
6.3.1.
.
.
.
,
. Python
.
. .
,
.
l i s t 1 = [ ' pick up g r o c e r i e s ' , 123,\
6.3.
67
6.3.1
.
list1 = [ ]
,
. list() ,
.
,
.
a = [1 ,2 ,3 ,4]
b = list (a)
c = [a]
print ( b )
print ( c )
list() . list()
, Python
.
a = [1 ,2 ,3 ,4]
6.
68
b = list (a)
c = a
print ( b )
print ( c )
# b i s a copy o f a and any change
# on i t doesn ' t a f f e c t a
b[0] = 5
print ( a )
# c i s a reference to a and a l l
# changes are r e f l e c t e d to a
c [ 0 ] = 10
print ( a )
6.3.2
, , ,
. .
,
list1[j] list1[j 1].
, n ,
list1[n] list1[n 1]
.
n = len ( l i s t 1 )
list1 [0]
6.3.
69
[i, j):
list1 [ i : j ]
,
.
10
( ) ,
:
a = [ x for x in range ( 1 0 ) ]
# or a = l i s t ( range ( 1 0 ) )
print ( a [ 2 : 8 : 2 ] )
[i, j) k
list1 [ i : j :k]
k
list1 [ : : k]
k ,
,
(
).
def reverse ( l i s ) :
return l i s [ : : 1 ]
6.
70
6.3.3
for.
a = [ 1 , 1 , 2 , 3 , 5 , 8]
for i in a :
print ( i )
, ,
.
a = [ 1 , 1 , 2 , 3 , 5 , 8]
b = iter (a)
p r i n t ( next ( b ) )
p r i n t ( next ( b ) )
p r i n t ( next ( b ) )
6.3.4
,
del
.
.
a = [ 0 , 1 , 2 , 3 , 4 , 5]
del a [ 2 : 4 ]
print ( a )
6.3.
6.3.5
71
(Lists comprehensions)
(list comprehensions). ,
.
.
primes = [ 1 , 2 , 3 , 5 , 7]
square_primes = [ i 2 for i in primes ]
print ( square_primes )
list comprehension
. .
:
r e s u l t = [ transform i t e r a t i o n f i l t e r ]
(transform)
1 (iteration) (filter), .
.
. ,
for, .
. , ,
, sum(). , 100
3 7.
nums = [ i for i in range ( 1 , 101) i f i % 3 == 0 or i % 7 == 0]
sum(nums) #2208
1
6.
72
6.3.6
,
. .
6.3.2. . :
6.4
6.4.1. . .
:
.
,
. , ,
.
a = ( 1 , ' asdf ' , 3.14)
print ( a )
6.5.
73
, .
,
.
6.5
(dictionary)
. 2 ,
,
,
( ) .
6.5.1
.
d = {
hash
.
6.
74
3.67) ,
1.67) ,
6.5.2
: (
/) len(d).
: ( )
d.keys().
: , d.values().
/ : /
d.items()
,
.
, .
,
,
, .
.
.
def increaseValue ( d , key , value ) :
" " " Increase value o f d [ key ] .
Precondition : We can add value to 0.
"""
6.5.
75
i f key not in d :
d [ key ] = 0
d [ key ] += value
.
, (
).
(value).
. get .
d[key]
.
value
d[key] .
6.
76
6.5.3
.
,
.
d = {
6.5.4
(mutable).
.
, copy().
d [ ' a ' ] = 123
c = d
c [ ' a ' ] = 1821
print ( d [ 'a ' ] )
:
6.5.
77
d = {}
d [ ' a ' ] = 123
c = d . copy ( )
c [ ' a ' ] = 1821
print ( d [ ' a ' ] )
6.5.5
(Dict comprehension)
, .
, {}
(iterable), .
.
d = { k : v for k , v in enumerate ( ' taspython ' ) i f v not in ' tas ' }
print ( d )
# { 8 : ' n ' , 3: ' p ' , 4: ' y ' , 6: ' h ' , 7: ' o ' }
# { 8 : ' n ' , 3: ' p ' , 4: ' y ' , 6: ' h ' , 7: ' o ' }
,
Python.
. , .
6.5.6
,
/ . , .
.
. . ,
6.
78
, .
(
),
.
from c o l l e c t i o n s import OrderedDict
d = OrderedDict ( )
d [ ' python ' ] = ' TasPython '
d [ ' guide ' ] = ' Greek '
p r i n t ( d . items ( ) )
6.6
, ,
, .
.
6.6.1
.
Python ,
.
s = { 'a ' , 'a ' , 'b ' , ' c ' , 'a ' }
print ( s )
(iterable).
6.6.
79
6.6.2
, :
.
a = set ( ' abracadabra ' )
b = set ( ' alacazam ' )
print ( ' A = ' , a )
print ( 'B = ' , b )
a . add ( ' z ' )
# add element
# remove element
# difference
# union
# intersection
# symmetric d i f f e r e n c e
80
6.
a = [ ' apple ' , ' bread ' , ' carrot ' , ' carrot ' ]
set1 = set ( a )
p r i n t ( set1 )
p r i n t ( ' apple ' in set1 )
set2 = set1 . copy ( )
set2 . add ( ' d e l i c i o u s ' )
p r i n t ( set1 < set1 )
set1 . remove ( ' bread ' )
# prints { ' carrot ' , ' apple ' }
p r i n t ( set1 & set2 )
# prints { ' carrot ' , ' apple ' , ' d e l i c i o u s ' , ' bread ' }
p r i n t ( set1 | set2 )
,
.
Python . ,
Python.
7.1
(immutable objects)
Python .
. , .
bool
int
81
7.
82
float
string
, .
id() 1
. is
True .
>>> a = 5
>>> b = 5
>>> c = 5.0
>>> d = ' 5 '
>>> id ( a )
137061184
>>> id ( d )
3073418688
>>> a i s b
True
>>> c i s d
False
, , a
is b .
.
,
.
1
,
, , .
7.2.
83
>>> a = 4
>>> b = 4
>>> a i s b
True
>>> a += 1
>>> a
5
>>> b
4
7.2
, , .
7.1. .
7.2. (scope).
. , , ,
.
7.3. (scope)
. (scope).
Python, . ,
(
) .
.
g = " I am a g l o b a l v a r i a b l e "
def function1 ( arg ) :
7.
84
a = " I am a l o c a l v a r i a b l e "
print ( g )
, Python
.
global.
g = " I am a g l o b a l v a r i a b l e "
def function1 ( arg ) :
global g
a = " I am a l o c a l v a r i a b l e "
print ( g )
g += ' modified '
print ( g )
p r i n t ( arg )
function1 ( "A reference to me i s passed . " )
-
7.2.
85
global,
.
g = " I am a g l o b a l v a r i a b l e "
def function1 ( arg ) :
g = " I thought I was g l o b a l "
prin t ( g )
function1 ( "A reference to me i s passed . " )
print ( g )
,
. ,
nonlocal global
. ,
.
def function1 ( ) :
a = " Scope1 v a r i a b l e "
def function2 ( ) :
nonlocal a
a += " modified "
print ( a )
function2 ( )
function1 ( )
nonlocal
.
7.
86
7.3
Python
(container types). :
(tuple)
(string)
(list)
(set)
(dictionary)
.
.
(alias) , .
>>> a = ' Python by example '
>>> b = ' Python by example '
>>> a i s b
False
>>> a = 1
>>> b = 2
>>> a i s b
False
>>> b = 1
>>> a i s b
True
is ==.
2 ==
.
2
,
.
7.3.
87
>>> a = [ 1 , 2 , 3]
>>> b = [ 1 , 2 , 3]
>>> a i s b
False
>>> a == b
True
7.3.1
(alias) , . , , ,
,
.
a = [ 1 , 2 , 3]
b = a
a . append ( 4 )
print ( b )
4 a, b, b
a .
7.3.2 None
None . Null.
Null Python
None.
def helloWorld ( ) :
prin t ( ' Hello World ' )
7.
88
p r i n t ( helloWorld ( ) == None )
None
. None
,
.
: None.
,
. ,
, None
.
p = [ 1 , 2 , 3 , 4]
print ( p )
# i l l e g a l statement because the returned value i s None
#p = p . pop ( )
p . pop ( )
print ( p )
7.4
(
) .
.
Python, , . ,
:
from f i l e import
python.py .
,
, -
7.4.
89
.
. ,
( )
.
7.4.1. (module) (, ). .py.
(
)
, ( ). (
python file.py) import
. Python ,
"__name__" "__main__".
"__name__"
.
from module import *
,
.
from module
import function ( ) import module,
module, module.variable, (
) /
.
. :
7.
90
.
.
.
namespace :
List1 = [ 1 , 2 , 3]
List2 = [ 1 , 2 , 3]
List2 [ 2 ] = "new"
List1 = { " a " : [ 1 ] , " b " : [ 2 ] }
aList
[0]
[1]
[2]
Namespace
7.1: (namespace) .
7.5
.
>>> def f ( a ) :
...
a = 5
...
>>> a = 4
>>> f ( a )
>>> a
4
7.5.
91
aList
[0]
[1]
[2]
bList
Namespace
7.2:
.
aList
"new"
[0]
[1]
[2]
bList
Namespace
7.3: .
[0]
[0]
aDict
Namespace
7.4: .
7.
92
a f
, . ,
a = 5 .
,
.
, L . , x
L. ,
x .
. , , L
, .
, , .
,
x . , L
foo()
.
def foo ( x ) :
p r i n t ( ' point 2: ' , end= ' ' )
p r i n t ( id ( x ) )
x = [ 1 , 2 , 3]
p r i n t ( ' point 3: ' , end= ' ' )
p r i n t ( id ( x ) )
print ( x )
L = [ 3 , 2 , 1]
p r i n t ( ' point 1: ' , end= ' ' )
p r i n t ( id ( L ) )
foo ( L )
p r i n t ( ' point 4: ' , end= ' ' )
p r i n t ( id ( L ) )
7.5.
93
print ( L )
, L .
L ,
.
foo() , L, python
L error
.
Python
.
def foo ( ) :
print ( ' point 2: ' , end= ' ' )
# Error . L i s not declared in t h i s scope
print ( id ( L ) )
L = [ 1 , 2 , 3]
print ( ' point 3: ' , end= ' ' )
print ( id ( L ) )
print ( L )
L = [ 3 , 2 , 1]
print ( ' point 1: ' , end= ' ' )
print ( id ( L ) )
foo ( )
print ( ' point 4: ' , end= ' ' )
print ( id ( L ) )
print ( L )
7.
94
:
.
, , , ,
, , .
def foo ( x ) :
p r i n t ( ' point 2: ' , end= ' ' )
p r i n t ( id ( L ) )
x . append ( 0 )
p r i n t ( ' point 3: ' , end= ' ' )
p r i n t ( id ( x ) )
print ( x )
L = [ 3 , 2 , 1]
p r i n t ( ' point 1: ' , end= ' ' )
p r i n t ( id ( L ) )
foo ( L )
p r i n t ( ' point 4: ' , end= ' ' )
p r i n t ( id ( L ) )
print ( L )
7.6
,
.
, deepcopy.
Python .
7.6.
95
In a more python
terms , i f sequence i s ' key ' , access : d [ ' k ' ] [ ' e ' ] [ ' y ' ] .
Assume that the d i c t i o n a r y i s at the ` position ` o f a l i s t ,
i f ` position ` i s an argument .
>>> a = { ' k ' : [ 0 , { ' a ' : [ 0 , { ' l ' : [ 0 , { ' o ' : [ 1 , { } ] } ] } ] } ] }
>>> a c c e s s _ t r i e ( a , ' kal ' , 1)
{ ' o ': [1 , { } ] }
>>> a c c e s s _ t r i e ( a , ' kalo ' , 1)
{}
>>> a = { ' p ' : { ' y ' : { ' t ' : { ' h ' : { ' o ' : { ' n ' :
{}}}}}}}
{}}}}
' ')
{ 'p ': { ' y ': { ' t ': { 'h ': { ' o ': { 'n ': { } } } } } } }
>>> a c c e s s _ t r i e ( a , ' python ' )
>>> a c c e s s _ t r i e ( a ,
{}
>>> b = a c c e s s _ t r i e ( a , ' pyth ' )
>>> b [ ' O ' ] = ' 123 '
>>> a
{ ' p ' : { ' y ' : { ' t ' : { ' h ' : { ' O ' : ' 123 ' , ' o ' : { ' n ' :
"""
for c in sequence :
d = d[ c ]
i f p o s i t i o n i s not None :
d = d [ position ]
{}}}}}}}
7.
96
return d
{}}}}}}}
>>> t r i e = { }
>>> p o p u l a t e _ t r i e ( t r i e , ' kalo ' , 1)
{ 'k ': [1 , { ' a ': [1 , { ' l ': [1 , { ' o ': [1 , { } ] } ] } ] } ] }
>>> t r i e = { }
>>> p o p u l a t e _ t r i e ( t r i e , ' heh ' , 2)
{ 'h ': [1 , 0, { ' e ': [1 , 0, { 'h ': [1 , 0, { } ] } ] } ] }
>>> t r i e = { }
>>> t r i e = p o p u la t e _ t r i e ( t r i e , ' heh ' , 1)
>>> p o p u l a t e _ t r i e ( t r i e , ' ha ' , 1)
{ 'h ': [2 , { ' a ': [1 , { } ] ,
"""
i f ( p o s i t i o n i s not None ) and ( p o s i t i o n >= 1 ) :
embedded_obj = [ 0 ] p o s i t i o n
embedded_obj . append ( { } )
else :
embedded_obj = { }
7.6.
97
d2 = t r i e
for i , character in enumerate ( sequence ) :
d2 = a c c e s s _ t r i e ( t r i e , sequence [ : i ] , p o s i t i o n )
i f character not in d2 :
i f p o s i t i o n i s None :
d2 [ character ] = deepcopy ( embedded_obj )
else :
d2 [ character ] = d2 . get ( character ,\
deepcopy ( embedded_obj ) )
d2 [ character ] [ 0 ] += 1
e l i f p o s i t i o n i s not None :
d2 [ character ] [ 0 ] += 1
return t r i e
access_trie()
. ,
position None, if
,
.
sequence
. ,
.
.
d (hides)
. ,
d
.
.
populate_trie , -
7.
98
deepcopy.
.
.
embedded_obj ,
.
embedded_obj
embedded_obj. .
, (
) .
:
>>> L = l i s t ( range ( 5 ) )
>>> L . append ( L )
>>> L
[0 , 1, 2, 3, 4, [ . . . ] ]
, 8.8,
8.3.
What can be said at all can be said clearly,
and what we cannot talk about we must pass
over in silence.
Ludwig Wittgenstein
, -
8.1
Python.
Ludwig Wittgenstein ,
:
. ()
. ( )
. ()
99
8.
100
, , , . (
)
. ( )
.
( )
,
. ( )
.
, ,
. ,
. ( )
,
.
.
.
, .
:
8.2.
101
(Class): (attributes)
(methods) . .
(Object): ,
.
.
(Instance): .
(Method): .
(Inheritance): ,
,
.
.
. (fields)
((methods).
.
.
8.2
8.
102
class Snake ( ) :
pass
python = Snake ( )
class Snake(): Snake
, python = Snake() .
.
class Snake ( ) :
def helloWorld ( s e l f ) :
p r i n t ( ' Hello World ! ' )
python = Snake ( )
python . helloWorld ( )
, , def. ,
self .
self,
.
, . .
(
)
.
, , . ( , ),
. ,
, .
, . , -
8.2.
103
, , ,
.
class Dog ( ) :
def _ _ i n i t _ _ ( s e l f , name, color , height , mood, age ) :
"""
This method i s c a l l e d when an new objected i s
initiallized .
"""
# here we setup the a t t r i b u t e s o f our dog
s e l f .name = name
s e l f . color = color
s e l f . height = height
s e l f .mood = mood
s e l f . age = age
s e l f . hungry = False
s e l f . t i r e d = False
def p r i n t _ a t t r i b u t e s ( s e l f ) :
" " " P r i n t a l l the a t t r i b u t e s o f the dog " " "
p r i n t ( 'Name i s ' , s e l f .name)
p r i n t ( ' Color i s ' , s e l f . c o l o r )
p r i n t ( ' Height i s ' , s e l f . height )
p r i n t ( ' Mood i s ' , s e l f .mood)
p r i n t ( ' Age i s ' , s e l f . age )
p r i n t ( ' Hungry i s ' , s e l f .name)
p r i n t ( ' Tired i s ' , s e l f . t i r e d )
ralph = Dog ( ' Ralph ' , ' blue ' , 1.80 , ' good ' , 15)
ralph . p r i n t _ a t t r i b u t e s ( )
,
Dog() -
8.
104
. __init__().
. __init__()
self ,
. .
8.2.1. , self this
. self
. , self
, . , ,
.
8.3
.
Trie
.
class T r i e :
"""
A T r i e i s l i k e a d i c t i o n a r y in that i t maps keys to values .
However , because o f the way keys are stored , i t allows
look up based on the longest p r e f i x that matches .
"""
def _ _ i n i t _ _ ( s e l f ) :
# Every node consists o f a l i s t with two p o s i t i o n .
In
8.3.
105
def i n s e r t ( s e l f , key ) :
"""
Add the given value f o r the given key .
>>> a = T r i e ( )
>>> a . i n s e r t ( ' kalo ' )
>>> p r i n t ( a )
[0 , { 'k ': [1 , { ' a ': [1 , { ' l ': [1 , { ' o ': [1 , { } ] } ] } ] } ] } ]
>>> a . i n s e r t ( ' kalo ' )
>>> p r i n t ( a )
[0 , { 'k ': [2 , { ' a ': [2 , { ' l ': [2 , { ' o ': [2 , { } ] } ] } ] } ] } ]
>>> b = T r i e ( )
>>> b . i n s e r t ( ' heh ' )
>>> b . i n s e r t ( ' ha ' )
>>> p r i n t ( b )
[0 , { 'h ': [2 , { ' a ': [1 , { } ] ,
"""
# f i n d the node to append the new value .
curr_node = s e l f . root
for k in key :
curr_node = curr_node [ 1 ] . s e t d e f a u l t ( k , [ 0 , { } ] )
curr_node [ 0 ] += 1
def f i n d ( s e l f , key ) :
"""
Return the value f o r the given key or None i f key not
found .
8.
106
>>> a = T r i e ( )
>>> a . i n s e r t ( ' ha ' )
>>> a . i n s e r t ( ' ha ' )
>>> a . i n s e r t ( ' he ' )
>>> a . i n s e r t ( ' ho ' )
>>> p r i n t ( a . f i n d ( ' h ' ) )
4
>>> p r i n t ( a . f i n d ( ' ha ' ) )
2
>>> p r i n t ( a . f i n d ( ' he ' ) )
1
"""
curr_node = s e l f . root
for k in key :
try :
curr_node = curr_node [ 1 ] [ k ]
except KeyError :
return 0
return curr_node [ 0 ]
def _ _ s t r _ _ ( s e l f ) :
return s t r ( s e l f . root )
def __getitem__ ( s e l f , key ) :
curr_node = s e l f . root
for k in key :
try :
curr_node = curr_node [ 1 ] [ k ]
except KeyError :
yield None
for k in curr_node [ 1 ] :
8.4. (attributes)
107
yield k , curr_node [ 1 ] [ k ] [ 0 ]
i f __name__ == ' __main__ ' :
a = Trie ( )
a . i n s e r t ( ' kalo ' )
a . i n s e r t ( ' kala ' )
a . i n s e r t ( ' kal ' )
a . i n s e r t ( ' kata ' )
prin t ( a . f i n d ( ' kala ' ) )
for b in a [ ' ka ' ] :
print ( b )
prin t ( a )
8.4
(attributes)
( ) (attributes) .
ralph (instance)
Dog,
name, ralph.name.
self .
() .
self.characteristic = .
, print_attributes(). self
.
.
8.
108
8.5
(member functions)
.
, , ,
(Member Functions). ,
.
.
.
Python :
v a r i a b l e . member_function ( [ any arguments required ] )
, dir Python
.
a = ' Python by example '
p r i n t ( ' Member functions f o r s t r i n g ' )
print ( dir ( a ) )
b = ( 1 , 2 , 3)
p r i n t ( ' Member functions f o r tuple ' )
print ( dir ( b ) )
c = [ 1 , 2 , 3]
p r i n t ( ' Member functions f o r l i s t ' )
print ( dir ( c ) )
__functionname__
Python
.
, -
8.6.
109
Python.
c = [ 1 , 2 , 3]
print ( help ( c . s o r t ) )
8.6
8.6.1
8.6.1.
( ).
.
class Snake :
noOfSnakes = 0
def _ _ i n i t _ _ ( s e l f , name = ' unknown ' ) :
s e l f .name = name
prin t ( ' I n i t i a l i z i n g { 0 } ' . format ( s e l f .name ) )
Snake . noOfSnakes += 1
def helloWorld ( s e l f ) :
prin t ( ' Hello World from { 0 } ! ' . format ( s e l f .name ) )
@staticmethod
def numberOfSnakes ( ) :
prin t ( Snake . noOfSnakes )
python = Snake ( ' TasPython ' )
python . helloWorld ( )
Snake . numberOfSnakes ( )
cobra = Snake ( )
cobra . helloWorld ( )
Snake . numberOfSnakes ( )
8.
110
. , (__init__,
noOfSnakes.
8.6.2
8.6.2. ,
. ,
( self).
,
(decorator) @staticmethod
. , ,
,
,
.
8.7
A b1 B . , B A, b1 1 . B 2 .
: (part-of) (has-a) - (is-a).
Python
.
1
fun
B a1.b1.fun(), a1 A.
2
a1.fun()
8.7.
111
.
8.7.1. .
. () ().
class UniversityMember :
def _ _ i n i t _ _ ( s e l f , name, age ) :
s e l f .name = name
s e l f . age = age
def who ( s e l f ) :
p r i n t ( 'Name : " { } " Age : " { } " ' . format ( s e l f .name, s e l f . age ) )
class Professor ( UniversityMember ) :
def _ _ i n i t _ _ ( s e l f , name, age , salary ) :
UniversityMember . _ _ i n i t _ _ ( s e l f , name, age )
s e l f . salary = salary
def who ( s e l f ) :
UniversityMember .who ( s e l f )
p r i n t ( ' Salary : " { } " ' . format ( s e l f . salary ) )
class Student ( UniversityMember ) :
def _ _ i n i t _ _ ( s e l f , name, age , marks ) :
UniversityMember . _ _ i n i t _ _ ( s e l f , name, age )
s e l f . marks = marks
def who ( s e l f ) :
UniversityMember .who ( s e l f )
p r i n t ( ' Marks : " { } " ' . format ( s e l f . marks ) )
8.
112
, ,
DRY Dont Repeat Yourself
,
(
).
8.8
,
( , ,
..).
__. .
,
8.8.
113
__init__(self, . . . ): .
. (base class) __init__(),
.
, __init__()
__del__(self): .
(destructor). ,
.
__repr__(self): repr() . ,
Python .
debugging.
__str__(self): str()
print().
__repr__() .
.
__lt__(self, other), __le__(self, other), __eq__(self, other), __ne__(self, other), __ne__(self, other), __gt__(self, other), __ge__(self, other): (<),
(<=), (==), (! =),
(>), (>=).
.
, , .
8.
114
__mul__(self, other): ()
__truediv__(self, other): (/)
__floordiv__(self, other): (//)
__mod__(self, other): (%)
,
(descriptors)
.
__, ,
.
:
class EmbeddedDict ( d i c t ) :
def __missing__ ( s e l f , key ) :
value = EmbeddedDict ( )
s e l f [ key ] = value
return value
d = {}
d2 = EmbeddedDict ( d )
d2 [ ' a ' ] [ ' b ' ] [ ' c ' ] = 1
p r i n t ( d2 )
, .
. -
,
.
9.1
, ,
. ,
open() . ,
,
. , , .
115
9.
116
open()
9.1.
r
( )
( )
r+ /
w
a
b
+
9.1:
r, w, a .
,
( r.
9.2
9.2.1
read().
, bytes
.
f = open ( ' i n p u t _ f i l e . t x t ' ) # open , readonly ( d e f a u l t )
p r i n t ( f .name) # recover name from f i l e o b j e c t
p r i n t ( f . readlines ( ) )
p r i n t ( f . readlines ( ) ) # already at end o f f i l e
f . seek ( 0 ) # go back to byte 0 o f the f i l e
p r i n t ( f . read ( ) ) # read to EOF, returning bytes in a s t r i n g
f . close ( )
9.2.
117
readlines read,
,
,
. , close()
.
9.2.2
, ,
,
open().
,
.
g = open ( ' n e w _ f i l e ' , 'w ' ) # open f o r w r i t i n g
g . write ( ' A new f i l e begins ' ) # takes j u s t one argument
g . write ( ' . . . today ! \n ' )
g . close ( )
, ,
.
f = open ( ' f i l e . t x t ' , ' a ' )
f . write ( ' Append a new l i n e at the end o f the f i l e \n ' )
f . close ( )
9.2.3
for
(iterate), .
f = open ( ' i n p u t _ f i l e . t x t ' ) # open , readonly ( d e f a u l t )
for l i n e in f :
prin t ( l i n e )
9.
118
, .
, , \n. , ,
. print ,
.
9.2.4
()
(serialization) , bits
( ) .
.
( ) .
, Python (module) pickle.
pickle
.
0:
1:
2: 2
Python
3:
( 3),
.
, .
9.3.
119
import p i c k l e
write_data = [ 1 , 2.0 , ' asdf ' , [ None , True , False ] ]
with open ( ' data . p i c k l e ' , ' wb ' ) as f :
p i c k l e .dump( write_data , f )
with open ( ' data . p i c k l e ' , ' rb ' ) as f :
read_data = p i c k l e . load ( f )
print ( read_data )
python
. ,
(binary format),
.
9.3
,
. python
,
.
os
( )
.
9.3.1
getcwd(): .
9.
120
listdir(): .
chdir(path): path.
(module)
os.
cross-platform,
.
. os.path.split()
os.path.join() crossplatform ,
.
import os
abs_path = os . path . abspath ( os . path . curdir )
# os . path . j o i n i s used to append a r e l a t i v e path at the
# end o f another path
path2 = os . path . j o i n ( abs_path , " new_dir " )
p r i n t ( path2 )
# os . path . s p l i t " s p l i t s " the path in two pieces .
# The path u n t i l the l a s t ' / ' and whatever f o l l o w s
path0 , path1 = os . path . s p l i t ( path2 )
p r i n t ( path0 )
p r i n t ( path1 )
( cross-platform) Python.
import os
p r i n t ( os . path . curdir ) # get current d i r e c t o r y ( Pythonic humor )
abs_path = os . path . abspath ( os . path . curdir ) # get i t s f u l l path
p r i n t ( abs_path )
9.3.
121
f u l l _ p a t h = os . getcwd ( )
print ( f u l l _ p a t h )
# get the t a i l end o f the path
print ( os . path . basename ( f u l l _ p a t h ) )
# l i s t the contents o f the current d i r e c t o r y
os . l i s t d i r ( f u l l _ p a t h )
# get information about f i l e . t x t
# the numbers below are : inode protection mode; inode number ;
# device inode resides on ; number o f l i n k s to the inode ;
# user id o f the owner ; group id o f the owner ; s i z e in bytes ;
# time o f l a s t access ; time o f l a s t modification ;
# " ctime " as reported by OS
print ( os . s t a t ( ' f i l e . t x t ' ) )
9.
122
.
9.3.2
mkdir(path): path.
makedirs(path): path
, .
import os
# remove new_dir i f already e x i s t s and i t i s empty
i f os . path . i s d i r ( ' new_dir ' ) :
os . rmdir ( ' new_dir ' )
os . makedirs ( ' new_dir ' )
p r i n t ( os . l i s t d i r ( ' . ' ) )
# change to subdirectory new_dir
os . chdir ( ' new_dir ' )
10
( ) -
. ,
.
10.1
10.1.1.
.
,
, .
123
10.
124
. ,
(
).
:
1. Python .
2. ( NameError, TypeError,
IndexError).
3. .
4. ,
.
5. , traceback,
.
,
, if. . . else . . . ,
. ,
,
else. ,
,
except.
10.2
,
.
.
>>> 8/0
Traceback ( most recent c a l l l a s t ) :
10.2. .
125
8/0
. . . except ZeroDivisionError :
...
...
Could not make the d i v i s i o n
, try ,
except.
(
ZeroDivisionError),
.
.
, :
>>> a 5
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
NameError : name ' a ' i s not defined
10.
126
a .
NameError.
, a,
try. . . except. . .
(NameError).
( )
.
>>> b = None
>>> b 7
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
TypeError : unsupported operand type ( s ) for :
f . read ( )
...
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
IOError : [ Errno 2] No such f i l e or d i r e c t o r y :
10.2. .
127
pass
-
except:, , .
import sys
try :
f = open ( ' myfile . t x t ' )
s = f . readline ( )
i = int ( s . strip ( ) )
except IOError as e r r :
prin t ( " I /O e r r o r : { } " . format ( e r r ) )
except ValueError :
prin t ( " Could not convert data to an i n t e g e r . " )
except :
prin t ( " Unexpected e r r o r : " , sys . exc_info ( ) [ 0 ] )
raise
, , , except . ,
myfile.txt,
.
, .
,
, IOError err.
. except
,
, except
10.
128
try, .
ValueError
.
, ,
raise,
.1 ,
, (
) .
raise .
10.3
, ( web )
, ,
.
.
while True :
try :
x = i n t ( input ( " Please enter a number : " ) )
break
except ValueError :
p r i n t ( " Not a number . Try again . . . " )
print ( x )
, . ,
, . ,
input 1
, ,
try. . . except. . .
.
10.4.
129
. , int
.
, x while, break
except ValueError,
. break ,
. ,
print.
10.4
,
Python.
1. try .
2. , except.
3. try ,
except.
4. except .
5. , .
6. , try .
7. , .
10.
130
try :
f = open ( ' myfile . t x t ' )
except IOError as e r r :
p r i n t ( " I /O e r r o r : { } " . format ( e r r ) )
else :
s = f . readline ( )
p r i n t ( ' The f i r s t l i n e o f f i s : ' , s )
f . close ( )
else
. , ,
.
:
1. try.
2. except.
3. ( ) else.
else
except .
10.4.2 finally
, finally,
, .
# how many times we have requested f o r input
times = 0
while True :
try :
x = i n t ( input ( " Please enter a number : " ) )
break
10.5.
131
except ValueError :
p r i n t ( " Not a number . Try again . . . " )
finally :
times += 1
print ( ' Requested input ' , times )
,
, . , finally,
,
.
.
10.5
10.5.1
2 Exception.
.
args
.
.
try :
r a i s e Exception ( ' Can you handle i t ? ' )
except Exception as i n s t :
prin t ( i n s t . args )
prin t ( i n s t )
2
10.
132
10.5.2
(raise)
,
BaseException. ,
, Exception. raise.
>>> r a i s e NameError ( ' TesseraPoulakiaKa8ontai ' )
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
NameError : TesseraPoulakiaKa8ontai
.
>>> r a i s e NameError
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
NameError
10.5.3
, Exception.
>>> class MyError ( Exception ) :
10.6. if . . . else
...
def _ _ i n i t _ _ ( s e l f , value ) :
...
s e l f . value = value
...
133
def _ _ s t r _ _ ( s e l f ) :
...
__str__
.
, ,
.
>>> try :
...
r a i s e MyError ( 4 )
. . . except MyError as e :
...
...
My exception occurred : 4
>>> r a i s e MyError ( ' oops ! ' )
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in ?
__main__ . MyError : ' oops ! '
10.6
if . . . else
.
if
. . . else. .
10.6.1.
,
. ,
10.
134
( ). , ,
.
.
from t i m e i t import Timer
from random import randint
VALUES = 10000
inverseprob = 2
d = d i c t ( [ ( x , y ) for x , y in z i p ( range (VALUES) , \
range (VALUES, 2 VALUES ) ) ] )
def i f _ e l s e ( d ) :
i f ' not ' in d :
d [ ' not ' ]
else :
pass
10.6. if . . . else
def try_exceptYES ( d ) :
try :
d[1]
except KeyError :
pass
def if_elseYES ( d ) :
i f 1 in d :
d[1]
else :
pass
def f a i l ( ) :
prin t ( " Unsuccessful look up" )
135
10.
136
t = Timer ( " try_except ( d ) " ,\
def success ( ) :
p r i n t ( " Successful look up" )
t = Timer ( " try_exceptYES ( d ) " ,\
" from __main__ import try_exceptYES , d " )
s f = ' Execution time with exceptions : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 6))
t = Timer ( " if_elseYES ( d ) " ,\
" from __main__ import if_elseYES , d " )
s f = ' Execution time with i f / e l s e : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 6))
def maybe ( ) :
p r i n t ( " Successful under a p r o b a b i l i t y " )
t = Timer ( " try_exceptMAYBE ( d , inverseprob ) " ,\
" from __main__ import try_exceptMAYBE , d , inverseprob " )
s f = ' Execution time with exceptions : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 6))
t = Timer ( " if_elseMAYBE ( d , inverseprob ) " ,\
" from __main__ import if_elseMAYBE , d , inverseprob " )
s f = ' Execution time with i f / e l s e : { } seconds '
10.6. if . . . else
prin t ( s f . format ( t . t i m e i t ( ) / 10 6))
def main ( ) :
success ( )
fail ()
maybe ( )
137
138
10.
11
, . ,
, .
( , ),
Python 3 .
11.1
(Iterators)
, (iterators).
, .
mylist = [ 1 , 2 , 3]
for i in mylist :
139
11.
140
print ( i )
(iterator) next() .
11.1.1
for
:
for i in mylist :
. . . loop body . . .
Python :
1. next(). iter(mylist)
next().
2.
. i
mylist. ,
next() i . i .
StopIteration next()
mylist
.
11.2
(generators)
yield return. . ,
yield. ,
yield, yield. ,
,
,
.
11.2.
141
11.2.1. iterators. ,
. , .
.
range() (end)
(start), modulo
.
def modulo_yield ( s t a r t , end , modulo ) :
" " " Create a l i s t o f a l l the number from s t a r t _ { modulo }
u n t i l end_ { modulo } i s reached .
"""
i f ( s t a r t > end ) :
a = s t a r t % modulo
b = ( end % modulo ) + modulo
else :
a = start
b = end
for num in range ( a , b ) :
yield num % modulo
start > end ,
. , yield
for. ,
, ,
.
Fibonacci
.
def f i b o n a c c i (num) :
a = 0
11.
142
yield a
b = 1
yield b
for i in range ( 2 , num) :
b, a = a + b, b
yield b
for i in f i b o n a c c i ( 1 0 ) :
print ( i )
, lists comprehensions.
primes = [ 1 , 2 , 3 , 5 , 7]
square_primes = ( i 2 for i in primes )
p r i n t ( next ( square_primes ) )
p r i n t ( next ( square_primes ) )
p r i n t ( next ( square_primes ) )
, ,
next(). next()
StopIteraton
.
,
.
( yield)
. ,
yield.
11.3.
11.3
143
. ,
(on the fly). ,
.
parsing
.
.
.
Fibonacci.
,
.
,
.. for,
.
:
1. len().
(
) for .
2. ( ) .
11.
144
,
:
for i in range ( 0 , len ( l ) ) :
e = l[i]
...
:
for i , e in enumerate ( l ) :
...
.
11.4
,
.
,
,
( ,
).
( 1, 17).
.
10
Fibonacci, 20,
Fibonacci.
. fibonacci
.
import i t e r t o o l s
class Indexable ( o b j e c t ) :
def _ _ i n i t _ _ ( s e l f , i t ) :
11.4.
145
self . it = it
def _ _ i t e r _ _ ( s e l f ) :
for e l t in s e l f . i t :
yield e l t
def __getitem__ ( s e l f , index ) :
try :
return next ( i t e r t o o l s . i s l i c e ( s e l f . i t , index ,\
index + 1 ) )
# support f o r [ s t a r t : end : step ] notation
except TypeError :
return l i s t ( i t e r t o o l s . i s l i c e ( s e l f . i t ,\
index . s t a r t , index . stop , index . step ) )
i t = Indexable ( f i b o n a c c i ( 4 5 ) )
# prints the 10th element
print ( i t [ 1 0 ] )
# 55
# prints the element a f t e r 10 elements from the current
print ( i t [ 1 0 ] )
# 10946
# prints the elements s t a r t i n g a f t e r where we had stopped
print ( i t [ 2 : 1 2 : 2 ] )
# [46368 , 121393, 317811, 832040, 2178309]
146
11.
12
, .
, (
).
(pattern).
Python.
. ,
. ,
.
12.1
1 . 1
147
12.
148
.
,
. ,
4.
import re
def num_start4 ( t e x t ) :
" " " Check whether any number which s t a r t s with 4. " " "
pattern = re . compile ( r ' \b4[0 9] ' )
return bool ( pattern . search ( t e x t ) )
a = num_start4 ( " asdf 1234" )
# False
# True
\. .
,
4 4321 4 3421.
. ,
.
import re
a = "3141/1000 reminds me o f pi "
b = re . f i n d a l l ( " [0 9] " , a )
13
, ,
,
-
13.1
( ) object.
(descriptors).
(attributes) .
, .
. ,
149
13.
150
x y .
,
getters setters
. , .
Python ,
. ,
.
13.2
13.2.1
. :
:
__set__(self, instance, value).
:
__delete__(self, instance).
13.2.
151
self
() ,
.
owner:
.
instance: ( )
. None
.
value: .
152
13.
14
GUI tkinter
. :
. .
GUI (Graphical
User Interface) .
.
:
1. wxPython
2. pyQT
3. PyGTK
4. tkinter
,
Python. , tkinter (= Tk interface) Python,
153
154
.
Tcl/Tk. tkinter
Tcl/Tk.
14.1
:
from t k i n t e r import
root = Tk ( )
w = Label ( root , t e x t = " Hello world ! " )
w. pack ( )
root . mainloop ( )
tkinter , ,
. (label)
pack(). ,
(mainloop)
.
14.2
,
. ,
, . , .
,
.
14.2.
155
from t k i n t e r import
from t k i n t e r . messagebox import
def d_result ( s e l f , c ) :
" " " Displays the r e s u l t o f an operation
"""
s e l f . label3 . c o n f i g ( t e x t = ' The r e s u l t i s ' + s t r ( c ) )
s e l f . label3 . pack ( )
def d_add ( s e l f ) :
" " " Handles the addition in the GUI
"""
a , b = s e l f . getNum ( )
c = s e l f . addition ( a , b )
s e l f . d_result ( c )
def d_sub ( s e l f ) :
" " " Handles the substraction in the GUI
"""
a , b = s e l f . getNum ( )
c = s e l f . substraction ( a , b )
s e l f . d_result ( c )
156
def d_mul ( s e l f ) :
def addition ( s e l f , a , b ) :
" " " Add numbers a , b and return t h e i r r e s u l t
"""
c = a + b
return c
def substraction ( s e l f , a , b ) :
" " " Substract a b and return the r e s u l t
"""
c = a b
return c
def m u l t i p l i c a t i o n ( s e l f , a , b ) :
" " " Multiply a b and return i t s r e s u l t
"""
c = a b
14.2.
157
return c
def d i v i s i o n ( s e l f , a , b ) :
" " " Divide a / b and return i t s r e s u l t
"""
try :
# i f b != 0
c = a / b
except ZeroDivisionError :
# i f b == 0
showinfo ( ' Warning ' , ' Cannot d i v i d e by 0. ' )
c = 0
return c
def getNum ( s e l f ) :
" " " Gets the two numbers on which the operation
w i l l be applied .
In case o f error , i t returns both o f them as zero
and warns the user .
"""
try :
a = f l o a t ( s e l f . enter1 . get ( ) )
b = f l o a t ( s e l f . enter2 . get ( ) )
# i f the f i e l d s were empty
except ValueError :
a, b = 0, 0
showinfo ( ' I n f o ' , ' There are some empty f i e l d s ' )
return a , b
158
two numbers
"""
# The f i r s t number
s e l f . label1 = Label ( s e l f , t e x t = l a b e l )
s e l f . label1 . pack ( )
# create the f i e l d f o r that number
s e l f . enter1 = Entry ( s e l f )
s e l f . enter1 . pack ( )
# the second number
s e l f . label2 = Label ( s e l f , t e x t = l a b e l )
s e l f . label2 . pack ( )
# create the f i e l d f o r the new number
s e l f . enter2 = Entry ( s e l f )
s e l f . enter2 . pack ( )
def drawGUI ( s e l f ) :
"""
I t draws the GUI within the container from which i s
c a l l e d . In t h i s case , within the frame where the
c a l c u l a t o r belongs .
"""
# draws the elements which are used to i n s e r t a number
s e l f . insertNum ( )
# set the focus to enter1
s e l f . enter1 . focus ( )
# create the buttons
s e l f . button1 = \
Button ( s e l f , t e x t = " add " , command = s e l f . d_add )
14.2.
s e l f . button2 = \
Button ( s e l f , t e x t = " sub " , command = s e l f . d_sub )
s e l f . button3 = \
Button ( s e l f , t e x t = "mul" , command = s e l f . d_mul )
s e l f . button4 = \
Button ( s e l f , t e x t = " div " , command = s e l f . d_div )
# display them
s e l f . button1 . pack ( side=LEFT )
s e l f . button2 . pack ( side=LEFT )
s e l f . button3 . pack ( side=LEFT )
s e l f . button4 . pack ( side=LEFT )
# create the l a b e l where we display the r e s u l t
s e l f . label3 = Label ( s e l f )
return root ;
root = Tk ( )
calc = Calculator ( master = root )
calc . mainloop ( )
159
160
Entry Button .
14.3
pop-up ,
. print
(
).
,
tkinter.messagebox. ,
.
showinfo()
askokcancel()
showwarning()
showerror()
askquestion()
askyesno()
askretrycancel()
14.3.
161
162
:
:
: . ,
.
,
.
from t k i n t e r import
from t k i n t e r . messagebox import
showinfo ( ' I n f o ' , ' There are some empty f i e l d s . ' )
showwarning ( ' Warning ' , ' A window detected ! ' )
showerror ( ' Error ' , ' Many windows have been detected ! ' )
askquestion ( ' I n s t a l l ' , ' Would you l i k e to i n s t a l l a door? ' )
( , ),
true false .
15
. ,
.
15.1
15.1.1
. .
, .
163
15.
164
,
.
15.1.2
15.1.3
,
.
. ,
!
Python DeBugger
165
(breakpoints)
Python.
15.2.1
, pdb.set_trace().
import pdb
a = " taspython "
b = " . eu\n"
pdb . s e t _ t r a c e ( )
c = " Because s i m p l i c i t y matters "
final = a + b + c
print ( f i n a l )
pdb.set_trace(),
n .
n,
enter
. debugger
q debugger c
.
15.2.2
n,
debugger ,
. s.
n,
15.
166
, .
s, r. , return
( ).
15.2.3
l p.
,
p ,
.
,
Python . , ,
.
,
Python. ,
(!)
debugger Python
.
15.2.4
15.1 debugger.
import pdb
pdb.set_trace()
<Enter>
q
p
c
l
s
r
167
debugger.
(quit)
(print)
(continue)
(listing)
(step into)
(return)
15.1:
168
15.
16
The only reason for time is so that everything
doesnt happen at once.
Albert Einstein
, .
. , ,
, . ; ,
. garbage collector
,
. ,
.
Python,
,
169
16.
170
, timeit. timeit,
,
. ,
,
.
, .
16.1
. 1 .
def measure_time ( ) :
from t i m e i t import Timer
s = """\
x = 5
i f x > 5:
p = 4
else :
p = 0
"""
t = Timer ( s )
print ( t . timeit ( ) )
timeit()
1.000.000 , ,
.
,
1
16.2.
171
number
timeit().
def measure_time ( ) :
from t i m e i t import Timer
s = """\
x = 5
i f x > 5:
p = 4
else :
p = 0
"""
t = Timer ( s )
prin t ( t . t i m e i t ( number=100000))
16.2
,
timeit.
Timer.
. (statements)2
.
def measure_time ( ) :
from t i m e i t import Timer
t = Timer ( " f a s t _ f u n c t i o n ( ) " ,\
" from __main__ import f a s t _ f u n c t i o n " )
s f = ' Execution time ( f o r each c a l l ) :
{ } seconds '
(;)
16.
172
fast_function(),
.
.
, fast_function Timer 106 ,
. ,
, t.timeit()
fast_function. ,
1000 .
t = Timer ( " f a s t _ f u n c t i o n ( ) " ,\
" from __main__ import f a s t _ f u n c t i o n " )
t . t i m e i t (1000)
,
106 ,
.
16.3
173
garbage collector
16.4
. Timer() .
3 .
, .
3
, pass
16.
174
,
.
def measure_time ( ) :
from t i m e i t import Timer
t = Timer ( ' f a s t _ f u n c t i o n ( a , b ) ' ,\
16.5.
175
, ,
.
16.5
; !
,
, ,
.
, (
)
:
python mtimeit s "SETUP_COMMANDS" "COMMAND_TO_BE_TIMED"
, . (Garbage Collector)
python mtimeit s ' f o r i in range ( 1 0 ) : oct ( i ) ' ' gc . enable ( ) '
16.6
(Profiling)
, ,
. , (Law of diminishing
returns).
,
.
.
176
16.