Upload
ion-capcanari
View
212
Download
3
Embed Size (px)
Citation preview
: :
ISBN 978-5-93286-157-8
9 785932 861578
Python Essential Reference
Fourth Edition
David Beazley
Python
- 2010
High tech
Python.
.
. . . . . . .
.
Python. . . . .: -, 2010. 864 ., .
ISBN 978-5-93286-157-8
Python. - Python. - ; , . , Python. - , , - .
Python, , , , . , - , , .
- , . - , Python 2.6 Python 3.
ISBN 978-5-93286-157-8 ISBN 978-0-672-32978-4 ()
-, 2010Authorized translation of the English edition 2009 Pearson Education, Inc. This trans lation is pub lished and sold by permission of Pearson Education, Inc., the owner of all rights to publish and sell the same.
, - . -, , .
-. 199034, -, 16 , 7,. (812) 324-5353, www.symbol.ru. N 000054 25.12.98.
30.07.2010. 70100 1/16. . 54 . . 1200 .
199034, -, 9 , 12.
, .
...............................................................................15
........................................................................17
................................................................................19
I. Python ..........................................21
1. ...........................................................23 ...........................................................23
..............................25
.............................................................28
- ..........................................29
................................................................................30
................................................................................32
..............................................................................33
...........................................................................35
...............................................................................36
................................................................37
.............................................................................39
..........................................................................40
.......................................................................41
.................................................................43
........................................................................44
...............................................................................46
...............................................................47
2. ...........................48 .....................................................48
...........................49
..............................................................50
.............................................................51
.........................................................................54
, ......................54
.....................................................55
.........................................................................55
..................................56
8
3. .......................................................57 ......................................................................57
...................................................58
.............................................59
....................................................................60
........................................................61
.................................63
.........................................75
............................80
..............................84
4. .....................................................96 ..........................................................96
.......................................99
........................................................ 103
..................... 105
...................................................... 108
................................................. 109
........................... 109
(.) ........................................... 110
() ................................................. 110
.................................................... 111
...................... 112
....................................... 113
........................................................... 113
.......................................................... 114
5. ... 116 .................................. 116
....................................................... 117
.............................................................. 117
...................................................................... 120
with .............................. 126
__debug__ ....................... 128
6. ............... 130 ........................................................................... 130
...................... 133
............................................................. 134
...................................... 136
....................................................................... 139
yield ............................................. 141
yield ........................................... 143
9
.............................. 146
............................................................ 148
- ....................................................... 150
........................................ 151
lambda ................................................................. 152
........................................................................... 153
................................................... 154
............................................................. 155
eval(), exec() compile() .......................................... 156
7. - .... 158 class ................................................................ 158
............................................................. 159
............................................................. 160
..................................................................... 160
, .................................................. 165
................................... 165
............................................................................ 167
...................................................................... 170
............................ 171
.............................................. 172
.................... 176
__slots__ ........................................................................... 177
........................................................ 178
............................ 180
................................................ 182
....................................................................... 184
8. , ........................................ 189 import ................................................ 189
......................... 191
.............. 193
........................................................... 194
........................................... 195
................................ 196
.............................................................................. 197
Python ......... 200
........................................... 203
9. ..................................................................... 205 ................................... 205
...................................................... 207
..................................................... 207
, ......... 211
10
print ............................................................... 212
print() .................................................................. 213
........................ 213
.............................................. 214
.................................................... 215
- ........................................................... 218
pickle ..................................... 223
10. ........................................................... 226 ............................... 226
........................................................ 229
Python ..................................... 230
.................. 231
........................... 232
........................................ 232
....................................................... 234
11. , , .. 236 doctest ............................ 236
unittest ............................. 239
Python pdb .............................................. 242
................................................ 247
.................................................... 248
II. Python ........................................ 257
12. ........................................................ 259 ................................................ 259
...................................................... 273
................................................ 278
future_builtins ........................................................ 279
13. Python ................................ 280 atexit ..................................................................... 280
copy ....................................................................... 280
gc .......................................................................... 281
inspect ................................................................... 283
marshal .................................................................. 288
pickle ..................................................................... 289
sys ......................................................................... 292
traceback ................................................................ 300
types ...................................................................... 301
warnings ................................................................. 303
weakref .................................................................. 305
11
14. ..................................................................... 309 decimal ................................................................... 309
fractions ................................................................. 317
math ...................................................................... 319
numbers ................................................................. 321
random ................................................................... 322
15. , .......................................... 326
abc ......................................................................... 326
array ...................................................................... 328
bisect ..................................................................... 331
collections ............................................................... 332
contextlib ............................................................... 339
functools ................................................................ 339
heapq ..................................................................... 341
itertools .................................................................. 342
operator .................................................................. 346
16. ............................................. 349 codecs .................................................................... 349
re .......................................................................... 354
string ..................................................................... 362
struct ..................................................................... 366
unicodedata ............................................................. 369
17. ..................................................... 375 ... 375
sqlite3 .................................................................... 383
DBM ............................. 391
shelve ..................................................................... 393
18. ........................................ 395 bz2 ........................................................................ 395
filecmp ................................................................... 396
fnmatch .................................................................. 398
glob ....................................................................... 399
gzip ....................................................................... 400
shutil ..................................................................... 400
tarfile .................................................................... 402
tempfile .................................................................. 407
zipfile .................................................................... 409
zlib ........................................................................ 413
19. ....................................... 415 commands ............................................................... 416
ConfigParser configparser ....................................... 416
12
datetime ................................................................. 421
errno ...................................................................... 430
fcntl ....................................................................... 434
io ........................................................................... 437
logging ................................................................... 445
mmap .................................................................... 463
msvcrt .................................................................... 467
optparse ................................................................. 469
os .......................................................................... 475
os.path ................................................................... 496
signal ..................................................................... 499
subprocess ............................................................... 503
time ....................................................................... 507
winreg .................................................................... 511
20. ............................................... 516 .............................................................. 516
Python ............................ 518
multiprocessing ....................................................... 519
threading ................................................................ 545
queue (Queue) .......................................................... 556
............................................... 559
21. .................................................... 561 ............................... 561
asynchat ................................................................. 564
asyncore ................................................................. 568
select ..................................................................... 572
socket ..................................................................... 586
ssl.......................................................................... 608
SocketServer ........................................................... 611
22. - ................................... 619 ftplib ..................................................................... 619
http ......................................................................... 623
smtplib ................................................................... 639
urllib ........................................................................ 640
xmlrpc ...................................................................... 651
23. - ................................................... 660 cgi ......................................................................... 662
cgitb ...................................................................... 670
WSGI ................................................................ 671
wsgiref ..................................................................... 673
13
24. .............. 677 base64 .................................................................... 677
binascii ................................................................... 680
csv ......................................................................... 681
email ........................................................................ 685
hashlib ................................................................... 694
hmac ...................................................................... 695
HTMLParser ........................................................... 696
json ....................................................................... 699
mimetypes .............................................................. 703
quopri .................................................................... 704
xml .......................................................................... 706
25. .................................... 725 Python ............................................ 725
................................................................. 726
............ 727
.................................................................................. 727
...................... 728
........................................................ 728
.................................................... 728
.............................................................. 729
III. ............................................... 731
26. Python ........... 733 ........................................................... 734
Python ..................................... 754
ctypes..................................................................... 759
.................................................. 768
Jython IronPython ............................................................ 769
A. Python 3 ........................................................ 770 Python 3? ...................................... 770
................................................... 771
.............................................................. 780
2to3 ............................ 788
......................................................... 794
. (David M. Beazley) Python, 1996 . , , - SWIG, - , C/C++, -, Python, Perl, Ruby, Tcl Java. - , PLY, - lex1 yacc2 Python. - - Python - . , . , , , , Python -. http://www.dabeaz.com.
1 . . .
2 . . .
(Noah Gift) Python For UNIX and Linux System Administration ( OReilly).1 - Google App Engine In Action ( Manning). , , -. , IBM developerWorks, Red Hat Magazine, OReilly MacTech. - http://www.giftcs.com, , http://noahgift.com. , - Twitter.
- , -, - , . Apple LPI. , Caltech, Disney Feature Animation, Sony Imageworks Turner Studios. Weta Digital, . , , - .
1 . , . Python UNIX Linux. . . .: -, 2009.
. , , . (Kurt Grandis) - . (Timothy Boronczyk), (Paul DuBois), (Mats Wichmann), (David Ascher) (Tim Bell) , . (Guido van Rossum), - (Jeremy Hylton), (Fred Drake), (Roger Masse) (Barry Warsaw) - , 1999 . , , . , , , . - Addison-Wesley Pearson Education . (Mark Taber), (Michael Thurston), (Seth Kerney) (Lisa Thibault) , - . (Robin Drake), . , - , .
, , -. , , - , , .
, , .
, -
, , -
, ,
.
, , . , .
: Mark Taber Associate Publisher Pearson Education 800 East 96th Street Indianapolis, IN 46240 USA
- informit.com/register, , .
- Python. -Python. -. - Python , -Python , - , - . , - Python Python. , Python , C Java. , -C Java. , - Java. , -Java. , -. , - (, ) .
Python http://www.python.org. , UNIX, Windows Macintosh. , - Python , - .
Python. -Python. -. - Python 2.6 Py-Python 2.6 Py- 2.6 Py-Py-thon 3.0. Python 3 - 3.0. Python 3 -Python 3 - 3 - . : Python 3.0 -Python 3.0 - 3.0 - Python 2.x, ?
, C, - . -, - , , , - . , . , - Python 2, Python 3. Python 3, (, ). , , Python -Python - - .
20
Python. - , .1 Python ; . - , - , , , , , -. , Python, . , . , - .
, , Python -Python - -. , . -, - . -, Python . - , , -. , - .
, , Python . - - Python, , -Python, , -, , - . .
(David Beazley)
,
, 2009
1 . Python. . . . : , 2000. . .
I. Python
1.
2.
3.
4.
5.
6.
7. -
8. ,
9.
10.
11. , ,
1.
- Python. , Python, . , , , , - , , , , -. . - . - , . Python Python 3, -Python Python 3, - Python 3, -Python 3, - 3, -, Python 2.6. , Python 3 - , , - . - - - -- Python 3.
Python . -Python . - . - python. - - (, Jython, IronPython, IDLE, ActivePython, Wing IDE, pydev ), . - , - , -. -, , - >>>, , :
24 1.
Python 2.6rc2 (r26rc2:66504, Sep 19 2008, 08:50:24)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type help, copyright, credits or license for more information.
>>> print ,
,
>>>
SyntaxError, , Py-Py-thon 3. - , , print Python 3 -Python 3 - 3 - . , . :
>>> print(, )
,
>>>
Python 2, -Python 2, - 2, -, . Python. , - , , , Python 2 Python 3.
Python . - . , , - Python . :
>>> 6000 + 4523.50 + 134.12
10657.620000000001
>>> _ + 8192.32
18849.940000000002
>>>
Python -Python - - _, - . . , - .
, , , :
# helloworld.py
print ,
25
Python -Python - - .py. # - , .
helloworld.py, , :
% python helloworld.py
,
%
Python Windows, .py (Run command), (Start). -, . , - ( , ). - Python, IDLE.
UNIX #!, :
#!/usr/bin/env python
print ,
, . - EOF (end of file ) Exit () Python. UNIX EOF Ctrl+D; Windows Ctrl+Z. - , SystemExit.
>>> raise SystemExit
1.1 , .
1.1.
principal = 1000 #
rate = 0.05 #
numyears = 5 #
year = 1
while year
26 1.
1 1050.0
2 1102.5
3 1157.625
4 1215.50625
5 1276.2815625
Python , . - . -, , . Python C, , , , . Python 1.1 principal. . - :
principal = principal * (1 + rate)
- principal. - principal 1000, ( rate - , ). principal . , , , principal, , .
. - , , :
principal = 1000; rate = 0.05; numyears = 5;
while , . , while. , -, , . , 1.1 - , while. Python , , - . ( ).
, 1.1, - .
27
, principal . - . - (%), :
print %3d %0.2f % (year, principal)
print(%3d %0.2f % (year, principal)) # Python 3
, :
1 1050.00
2 1102.50
3 1157.63
4 1215.51
5 1276.28
, %d, %s %f. - , . - , - . , %3d , - 3 , %0.2f , . - printf() C - 4 .
- , format(). :
print format(year,3d),format(principal,0.2f)
print(format(year,3d),format(principal,0.2f)) # Python 3
format() , (%). -, 3d , - 3 , 0.2f , . , for-mat(), - . :
print {0:3d} {1:0.2f}.format(year,principal)
print({0:3d} {1:0.2f}.format(year,principal)) # Python 3
{0:3d} {1:0.2f} format(), .
28 1.
if else. -:
if a < b:
else:
if else . else - .
, , - pass, :
if a < b:
pass #
else:
or, and not:
if product == and type == \
and not (age < 4 or age > 8):
print !
. , - , (\) , . - , , - , .
Python , switch case. - , elif, :
if suffix == .htm:
content = text/html
elif suffix == .jpg:
content = image/jpeg
elif suffix == .png:
content = image/png
else:
raise RuntimeError( )
True False Boolean. :
if spam in s:
has_spam = True
- 29
else:
has_spam = False
, < >, True False. - in, , , -, . True False, - , :
has_spam = spam in s
- :
f = open(foo.txt) #
line = f.readline() # readline()
while line:
print line, # ,
# print(line,end=) # Python 3
line = f.readline()
f.close()
open() . , . read-line() , . .
foo.txt. , - (, , , - ), . , Python for, - . , - :
for line in open(foo.txt):
print line,
, print - >> , :
f = open(out,w) #
while year >f,%3d %0.2f % (year,principal)
year += 1
f.close()
>> Python 2. Python 3 print , :
print(%3d %0.2f % (year,principal),file=f)
30 1.
, write(), - . , - print - :
f.write(%3d %0.2f\n % (year,principal))
, -. , - , sys.stdin. , sys.stdout, print. :
import sys
sys.stdout.write( :)
name = sys.stdin.readline()
Python 2 , :
name = raw_input( :)
Python 3 raw_input() input(), .
, , , :
a = , !
b = Python
c =
, - . , , - . - , , :
print Content-type: text/html
Hello World
Click here.
, , . - , s[i], :
31
a = ,
b = a[4] # b =
, s[i:j]. s k i >> x = 3.4
>>> str(x)
3.4
>>> repr(x)
3.3999999999999999
>>>
3.4 - Python. , - - .
32 1.
format(). :
>>> format(x,0.5f)
3.40000
>>>
. - , :
names = [ Dave, Mark, Ann, Phil ]
, , . :
a = names[2] # , Ann
names[0] = Jeff # Jeff
ap-pend():
names.append(Paula)
insert():
names.insert(2, Thomas)
:
b = names[0:2] # [Jeff, Mark]
c = names[2:] # [Thomas, Ann, Phil, Paula]
names[1] = Jeff # Jeff
names[0:2] = [Dave,Mark,Jeff] #
# .
(+) :
a = [1,2,3] + [4,5] # [1,2,3,4,5]
:
names = [] #
names = list() #
, , :
a = [1,Dave,3.14, [Mark, 7, 9, [100,101]], 10]
- , :
33
a[1] # Dave
a[3][2] # 9
a[3][3][1] # 101
1.2 . , , - .
1.2.
import sys # sys
if len(sys.argv) != 2 : # :
print ,
raise SystemExit(1)
f = open(sys.argv[1]) # ,
lines = f.readlines() #
f.close()
#
fvalues = [float(line) for line in lines]
#
print : , min(fvalues)
print : , max(fvalues)
import - sys Python. -Python. -. - .
open() , - sys.argv. readlines() - .
[float(line) for line in lines] , - float() . , , - . - for, , , :
fvalues = [float(line) for line in open(sys.argv[1])]
, - , min() max() .
-, -. , :
stock = (GOOG, 100, 490.10)
34 1.
address = (www.python.org, 80)
person = (first_name, last_name, phone)
Python , -Python , - , - :
stock = GOOG, 100, 490.10
address = www.python.org,80
person = first_name, last_name, phone
, -, 0 1 , :
a = () # ( )
b = (item,) # ( )
c = item, # ( )
-, . , :
name, shares, price = stock
host, port = address
first_name, last_name, phone = person
, ( , ), ( , - ). , , , .
- , - . , , ( ), - , . - , , , , . , , . . - .
. , , - , :
# name,shares,price
filename = portfolio.csv
portfolio = []
35
for line in open(filename):
fields = line.split(,) #
name = fields[0] #
shares = int(fields[1])
price = float(fields[2])
stock = (name,shares,price) # (name, shares, price)
portfolio.append(stock) #
split() - . portfolio, -, . , :
>>> portfolio[0]
(GOOG, 100, 490.10)
>>> portfolio[1]
(MSFT, 50, 54.23)
>>>
:
>>> portfolio[1][1]
50
>>> portfolio[1][2]
54.23
>>>
:
total = 0.0
for name, shares, price in portfolio:
total += shares * price
. set(), - , :
s = set([3,5,9,10]) #
t = set(Hello) #
, - - . , . , , - , :
>>> t
set([H, e, l, o])
, l.
36 1.
, , , . :
a = t | s # t s
b = t & s # t s
c = t s # (, t, s)
d = t ^ s # (, t s,
# )
add() update() :
t.add(x) #
s.update([10,37,42]) # s
remove():
t.remove(H)
, , , . , - ({}), :
stock = {
name : GOOG,
shares : 100,
price : 490.10
}
- :
name = stock[name]
value = stock[shares] * stock[price]
:
stock[shares] = 75
stock[date] = June 7, 2007
, , Py-Py-thon, . , , , - .
, , . , , , . , :
37
prices = {
GOOG : 490.10,
AAPL : 123.50,
IBM : 91.50,
MSFT : 52.13
}
:
prices = {} #
prices = dict() #
- in, :
if SCOX in prices:
p = prices[SCOX]
else:
p = 0.0
:
p = prices.get(SCOX,0.0)
, :
syms = list(prices) # syms = [AAPL, MSFT, IBM, GOOG]
del:
del prices[MSFT]
, , Python. - , -, .
for, - . Python. -Python. -. - -, , . :
for n in [1,2,3,4,5,6,7,8,9]:
print 2 %d = %d % (n, 2**n)
n - [1,2,3,4,,9]. - , :
38 1.
for n in range(1,10):
print 2 %d = %d % (n, 2**n)
range(i,j [,stride]) , - i j-1. , . stride - . :
a = range(5) # a = 0,1,2,3,4
b = range(1,8) # b = 1,2,3,4,5,6,7
c = range(0,14,3) # c = 0,3,6,9,12
d = range(8,1,-1) # d = 8,7,6,5,4,3,2
range() Python 2, . -. Python -Python - - xrange(). :
for i in xrange(100000000): # i = 0,1,2,...,99999999
xrange() , . - . Python 3 xrange() range(), range() .
for , , , , . :
a = ,
# a
for c in a:
print c
b = [Dave,Mark,Ann,Phil]
#
for name in b:
print name
c = { GOOG : 490.10, IBM : 91.50, AAPL : 123.15 }
#
for key in c:
print key, c[key]
#
f = open(foo.txt)
for line in f:
print line,
for Python, - -, . -
39
, - 6 .
def, :
def remainder(a, b):
q = a // b # // .
r = a - q*b
return r
, , , : result = re- = re-re-mainder(37, 15). , , :
def divide(a, b):
q = a // b # a b , q
r = a - q*b
return (q,r)
, - , :
quotient, remainder = divide(1456, 33)
:
def connect(hostname, port, timeout=300):
#
- - , . - , . :
connect(www.python.org, 80)
-, . , - . :
connect(port=80, hostname=www.python.org)
, - . , , - . - , global:
40 1.
count = 0
...
def foo():
global count
count += 1 # count
, yield, . :
def countdown(n):
print !
while n > 0:
yield n # (n)
n -= 1
, yield, -. - , - next() ( __next__() Python 3). :
>>> c = countdown(5)
>>> c.next()
!
5
>>> c.next()
4
>>> c.next()
3
>>>
next() - , yield. next() - , yield, . next() - , , yield. , .
, next() , . - - for, :
>>> for i in countdown(5):
... print i,
!
5 4 3 2 1
>>>
- . , - - tail -f, -
41
UNIX :
# ( tail -f)
import time
def tail(f):
f.seek(0,2) #
while True:
line = f.readline() #
if not line: # ,
time.sleep(0.1) #
continue #
yield line
, :
def grep(lines, searchtext):
for line in lines:
if searchtext in line: yield line
, - :
# tail -f | grep python
# Python
wwwlog = tail(open(access-log))
pylines = grep(wwwlog,python)
for line in pylines:
print line,
, - , . , , for item in s, s , , - - , -. s .
-. , , , . , yield, (yield), - :
def print_matches(matchtext):
print , matchtext
while True:
line = (yield) #
42 1.
if matchtext in line:
print line
, - , - (yield), send(). :
>>> matcher = print_matches(python)
>>> matcher.next() # (yield)
python
>>> matcher.send(Hello World)
>>> matcher.send(python is cool)
python is cool
>>> matcher.send(yow!)
>>> matcher.close() # matcher
>>>
, send(). , (yield) . -, (yield) . -, , close(), .
-, --, , . - . , :
#
matchers = [
print_matches(python),
print_matches(guido),
print_matches(jython)
]
# next()
for m in matchers: m.next()
# .
# : ,
# - .
wwwlog = tail(open(access-log))
for line in wwwlog:
for m in matchers:
m.send(line) #
6.
43
, , . , - . - , , . :
items = [37, 42] #
items.append(73) # append()
dir() . :
>>> items = [37, 42]
>>> dir(items)
[__add__, __class__, __contains__, __delattr__, __delitem__,
...
append, count, extend, index, insert, pop,
remove, reverse, sort]
>>>
, append() insert(). , - , . . , __add__() +:
>>> items.__add__([73,101])
[37, 42, 73, 101]
>>>
- class. , - , push(), pop() length():
class Stack(object):
def __init__(self): #
self.stack = [ ]
def push(self,object):
self.stack.append(object)
def pop(self):
return self.stack.pop()
def length(self):
return len(self.stack)
class Stack(object) -, Stack . , ; Stack object, - Python. -Python. -. - , def. -
44 1.
. self. , , self. , -, . , __init__() - .
:
s = Stack() #
s.push(Dave) #
s.push(42)
s.push([3,4,5])
x = s.pop() # x [3,4,5]
y = s.pop() # y 42
del s # s
, . . - list - :
class Stack(list):
# push()
# : pop().
def push(self,object):
self.append(object)
, , - ( -). , , C++ Java:
class EventHandler(object):
@staticmethod
def dispatcherThread():
while (1):
#
...
EventHandler.dispatcherThread() #
@staticmethod -. @staticmethod , 6.
- , , :
Traceback (most recent call last):
File foo.py, line 12, in
IOError: [Errno 2] No such file or directory: file.txt
45
(:
( ):
foo.py, 12,
IOError: [Errno 2] : file.txt
)
, . . - try except, :
try:
f = open(file.txt,r)
except IOError as e:
print e
IOError, - e - except. - , ( ). , except . , except. , - .
raise. raise -, :
raise RuntimeError( )
, 5 - .
, , - , , . - - with, . , -:
import threading
message_lock = threading.Lock()
...
with message_lock:
messages.add(newmessage)
with - message_lock. with, . , , with. , -
46 1.
, .
with , - , , . - . - 3 .
- , . Python , -. , , - . ( , .py.) :
# : div.py
def divide(a, b):
q = a/b # a b , q
r = a - q*b
return (q, r)
import:
import div
a, b = div.divide(2305, 29)
import - , - .py. , - , div.divide() .
, import as, - :
import div as foo
a,b = foo.divide(2305,29)
, from:
from div import divide
a,b = divide(2305,29) # div
, :
47
from div import *
dir() - , - :
>>> import string
>>> dir(string)
[__builtins__, __doc__, __file__, __name__, _idmap,
_idmapL, _lower, _swapcase, _upper, atof, atof_error,
atoi, atoi_error, atol, atol_error, capitalize,
capwords, center, count, digits, expandtabs, find,
...
>>>
Python -Python - - . -, - help() Python. -Python. -. - help() help(_), -. help() , .
Python -Python - -, . - , __doc__. :
>>> print issubclass.__doc__
issubclass(C, B) -> bool
Return whether class C is a subclass (i.e., a derived class) of class B.
When using a tuple as the second argument issubclass(X, (A, B, ...)),
is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).
(
, C ( ) B.
issubclass(X, (A, B, ...)),
issubclass(X, A) or issubclass(X, B)
or ... ( . .).
)
>>>
, Py-Py-thon pydoc, Python. pydoc topic .
2.
, Python. , , - , , , - .
. , - (\), :
a = math.cos(3 * (x - n)) + \
math.sin(3 * (y - n))
-, , . , (...), [...], {...} , , .
, , , - . , . :
if a:
1 #
2
49
else:
3
4 # ()
, , , - , :
if a: 1
else: 2
pass. :
if a:
pass
else:
, . Py-Py-thon ( ) . Python , -Python , - , - , , 8 (, 11, 16). Python -t, , -, - . -tt, TabError.
-, (;). , , , .
# , -. , # , .
, , . .
, -, , , . - (_), .
50 2.
- AZ az ISO-Latin. -AZ az ISO-Latin. -Z az ISO-Latin. -Z az ISO-Latin. - az ISO-Latin. -az ISO-Latin. -z ISO-Latin. -z ISO-Latin. - ISO-Latin. -ISO-Latin. --Latin. -Latin. -. - , FOO foo . , $, % @. , , if, else for - . :
and del from nonlocal try
as elif global not while
assert else if or with
break except import pass yield
class exec in print
continue finally is raise
def for lambda return
, -, . , , - , _foo, - from module import *. , , __init__, . , - , __bar, - , 7 - -. .
Python :
True False , 1 0 . , 1234, . - , , 0, 0x 0b (, 0644, 0x100fea8 0b11101010).
Python , , , , , : 12345678901234567890.
51
1 , l ( L ) L, : 12345678901234567890L. - L , Python , - , , . Python, , L. -. , , ( L).
, 123.34 1.2334e+02, - . , j J, 12.34J, . , , : 1.2 + 12.34J.
, (), - () ( ). , - , , . - , - - ( , , ). ( , - ), hello world, - , : helloworld.
(\) , , , . - . 2.1. .
2.1.
\
\\
\
1 , repr(). . .
52 2.
\
\a
\b
\e
\0
\n
\v
\t
\r
\f
\OOO ( \000 \377)
\uxxxx ( \u0000 \uffff)
\Uxxxxxxxx ( \U00000000 \Uffffffff)
\N{ }
\xhh ( \x00 \xff)
\OOO \x , ( , , , ). - , . , Jalapeo, , Jalape\xf1o, \xf1 . Python 2 8- . . Python 2 . , , u . :
s = uJalape\u00f1o
Python 3 ( -Python 3 ( - 3 ( - ), - . Python 2 , -U ( - -, u ).
2.1 ()
53
Python -Python - - \u, \U \N . 2.1 - . , - U+XXXX, XXXX - . ( : Python, -Python, -, - .) , U+00F1. \u - U+0000 U+FFFF (-, \u00f1). \U U+10000 (-, \U00012345). \U , U+10000 , - . 3 .
, . - , \N{ }. :
s = uJalape\N{LATIN SMALL LETTER N WITH TILDE}o
http://www.unicode.org/charts.
r R, : r\d. , - , , . , , - . - , - re, Windows (, rc:\newdata\tests).
, r\. \uXXXX - , , \, - . , ur\u1234 - U+1234, ur\\u1234 , , u1234. , Py-Py-thon 2.2 r u, -. Python 3.0 u .
,
54 2.
, UTF-8 UTF-16. , UTF-8, Jalape\xc3\xb1o, - U+004A, U+0061, U+006C, U+0061, U+0070, U+0065, U+00C3, U+00B1, U+006F, , , . , UTF-8 \xc3\xb1 U+00F1, U+00C3 U+00B1. -, b, : bJalape\xc3\xb1o. , - . , decode(). 3 4 .
, - Python 2.6, . Python 3 bytes, (. - A, Python 3).
, [...], (...) {...} , , , , :
a = [ 1, 3.4, hello ] #
b = ( 10, 20, 30 ) #
c = { a: 3, b: 42 } #
, - , (\). , - . :
a = [ 1,
3.4,
hello,
]
,
Python :
+ - * ** / // % > & |
^ ~ < > = == != +=
-= *= /= //= %= **= &= |= ^= >>=
55
, , :
( ) [ ] { } , : . ` = ;
, (=) -, (,) , . (.) - , (...) - .
, :
# \ @
$ ? - , .
, - , , , :
def fact(n):
if (n >> print fact._ _doc__
>>>
- , . , . - .
, - , , , , . @ , - , . :
56 2.
class Foo(object):
@staticmethod
def bar():
pass
, . :
@foo
@bar
def spam():
pass
6 7 - .
Python -Python - - 7- ASCII. , , -, - .
Python , , :
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
s = Jalapeo # UTF-8. coding: - , -, . Python, -Python, -, - , ASCII.
3.
, Python, . , , , . - . , . Python . - 4 . - 7 - .
, Python, - . , ( ) . , a = 42, 42. , , a , .
, , , . . . , . , . , - , , -.
. , .
58 3.
, , -, . - (.), :
a = 3 + 4j #
r = a.real # ()
b = [1, 2, 3] #
b.append(7) # append
#
, , id(). , , - Python, -Python, -, - . is . type() . :
#
def compare(a,b):
if a is b:
# a b
if a == b:
# a b
if type(a) is type(b):
# a b
, . - . - is. , . , list, dict file, - . :
if type(s) is list:
s.append(item)
if type(d) is dict:
d.update(t)
, - isinstance(object, type). :
if isinstance(s,list):
s.append(item)
59
if isinstance(d,dict):
d.update(t)
isinstance() , Python.
, , . -, . -, , - . , isinstance(s,list) , , , , , -, list. , , . - - - - - -- 7.
. , , , , :
a = 37 # 37
b = a # 37
c = []
c.append(b) # 37
, 37. a, , . - a b, b , 1. , b , - . , 37. - .
, del ( - ). :
del a # 37
b = 42 # 37
c[0] = 2.0 # 37
- sys.getrefcount(). :
>>> a = 37
>>> import sys
60 3.
>>> sys.getrefcount(a)
7
>>>
, . , , - , .
, - . , -. :
a = { }
b = { }
a[b] = b # a b
b[a] = a # b a
del a
del b
del a b , . - , - ( - ). , , . , -, - . gc (. 13, Python ).
, a = b, - b. , , b. , , . :
>>> a = [1,2,3,4]
>>> b = a # b a
>>> b is a
True
>>> b[2] = -100 # b
>>> a # , a
[1, 2, -100, 4]
>>>
61
a b , - , , . , .
, , - : -. , , . :
>>> a = [ 1, 2, [3,4] ]
>>> b = list(a) # a.
>>> b is a
False
>>> b.append(100) # b.
>>> b
[1, 2, [3, 4], 100]
>>> a # , a
[1, 2, [3, 4]]
>>> b[2] [0] = -100 # b
>>> b
[1, 2, [-100, 4], 100]
>>> a # , a
[1, 2, [-100, 4]]
>>>
a b , , , . - a b.
- , . Python , . - copy.deepcopy(), - :
>>> import copy
>>> a = [1, 2, [3, 4]]
>>> b = copy.deepcopy(a)
>>> b[2] [0] = -100
>>> b
[1, 2, [-100, 4]]
>>> a # , a
[1, 2, [3, 4]]
>>>
Python -Python - -. , , , - . , , -
62 3.
, , . , , :
items = {
number : 42
text : Hello World
}
, . :
items[func] = abs # abs()
import math
items[mod] = math #
items[error] = ValueError #
nums = [1,2,3,4]
items[append] = nums.append #
, , . - , . -:
>>> items[func](-45) # abs(-45)
45
>>> items[mod].sqrt(4) # math.sqrt(4)
2.0
>>> try:
... x = int(a lot)
... except items[error] as e: # except ValueError as e
... print(Couldnt convert)
...
Couldnt convert
>>> items[append](100) # nums.append(100)
>>> nums
[1, 2, 3, 4, 100]
>>>
, Python -Python - - , , -. , , , GOOG,100,490.10, , . - : ( ) - :
>>> line = GOOG,100,490.10
>>> field_types = [str, int, float]
>>> raw_fields = line.split(,)
>>> fields = [ty(val) for ty,val in zip(field_types,raw_fields)]
>>> fields
[GOOG, 100, 490.10000000000002]
>>>
63
Python , -Python , - , - . , . 3.1. , - , isinstance(). Python 2, ( Py-Python 2, ( Py- 2, ( Py-Py-thon 3 ).
3.1.
None type(None) None.
int
long
float
complex
bool
( Python 2)
(True False)
str
unicode
list
tuple
xrange
( Python 2)
, xrange() ( Python 3 range)
dict
set
frozenset
None None (, ). Python -Python - -, None. - , . None , , - . None - False.
64 3.
Python : , , , . , - . - .
: True False. True False 1 0 . - 2147483648 2147483647 ( ). ( -). , , Python (-Python (- (-, Python 3 ). , , , , - . - - . Python 2 isinstance(x, int) False, x .
Python - (64 ). , IEEE 754, -IEEE 754, - 754, - 17 , 308 308. double - C. Python 32- . - , numpy ( : http://numpy.sourceforge.net).
. - z z.real z.imag. z.conjugate() - z ( a+bj a-bj).
, . ( - fractions) numerator denominator. - real imag, conjugate(). , - , as_integer_ratio(). is_integer() ,
65
. hex() fromhex() - .
- . decimal - . fractions . 14 .
, - . , -. , . ; -, . .
,
. 3.2 , - . i- s s[i]. s[i:j] s[i:j:stride] ( 4). len(s). - min(s) max(s). -, , ( ). sum(s) , .
. 3.3 , - . 3.3 , -. 3.3 , -. 3.3 , -3.3 , - , .
3.2. ,
s[i] i- s
s[i:j]
s[i:j:stride]
len(s) s
min(s) - s
max(s) - s
66 3.
sum(s [,initial]) s
all(s) , - s, True
any(s) , - s, True
3.3. ,
s[i] = v
s[i:j] = t
s[i:j:stride] = t
del s[i]
del s[i:j]
del s[i:j:stride]
, , . 3.4. list(s) . s , , - . s.append(x) - x. s.index(x) x. - ValueError. s.remove(x) x Val-ueError, . s.extend(t) - s, t.
s.sort() . - . , . -, , . s.reverse() . , sort() reverse(), None.
3.2 ()
67
3.4.
list(s) s .
s.append(x) x s.
s.extend(t) t s.
s.count(x) x s.
s.index(x [,start [,stop]]) i, s[i] == x. start stop - , .
s.insert(i,x) x i.
s.pop([i]) i- . i , .
s.remove(x) s x - .
s.reverse() s .
s.sort([key [, reverse]]) s. key , . reverse - . key reverse - .
Python 2 . -Python 2 . - 2 . - , 8- . NULL. -, 16- . - -- 65 536 . 1 , Python . , (4--) , ; . - Python 32- . , Python U+000000 U+110000. , , - .
, . 3.5. , -
68 3.
, . -, s.capitalize(), s.center() s.expandtabs(), s . , s.isalnum() s.isupper(), True False, - . , - False .
s.find(), s.index(), s.rfind() s.rindex() . - s. , , find() -1, index() ValueError. s.replace() . , -. - re.
s.split() s.rsplit() -, . s.partition() s.rpartition() - - s : , - .
start end, , - s. , - .
s.translate() , , . , - -- - . 8- 256- . s, s[n] , - n.
s.encode() s.decode() , : ascii, utf-8 utf-16. - , - - 9 . , Python 3 encode() , decode() bytes.
s.format() . . - s {item} . {0}, {1} . . {name}, name . :
69
>>> a = {0} {age}
>>> a.format(, age=40)
40
>>>
{item} - . {item[n]}, n , n- item. - {item[key]}, key , item[key]. {item.attr} - attr item. format() - 4.
3.5.
s.capitalize() -.
s.center(width [, pad]) width. pad , .
s.count(sub [,start [,end]]) sub.
s.decode([encoding [,errors]]) ( ).
s.encode([encoding [,errors]]) ( ).
s.endswith(suffix [,start [,end]]) , - suffix.
s.expandtabs([tabsize]) .
s.find(sub [, start [,end]]) sub -1.
s.format(*args, **kwargs) s.
s.index(sub [, start [,end]]) sub .
s.isalnum() , - - .
s.isalpha() , - .
s.isdigit() , - .
s.islower() , - .
s.isspace() , - .
70 3.
s.istitle() , .
s.isupper() , - .
s.join(t) , - t, s -.
s.ljust(width [, fill]) s width.
s.lower() .
s.lstrip([chrs]) , chrs.
s.partition(sep) - sep. (head,sep,tail) (s, ,), sep s.
s.replace(old, new [,maxreplace]) old new.
s.rfind(sub [,start [,end]]) .
s.rindex(sub [,start [,end]]) .
s.rjust(width [, fill]) s width.
s.rpartition(sep) - sep, .
s.rsplit([sep [,maxsplit]]) , , - sep. maxsplit . maxsplit -, split().
s.rstrip([chrs]) , chrs.
s.split([sep [,maxsplit]]) - sep. maxsplit - .
s.splitlines([keepends]) . keepnds 1, - .
3.5 ()
71
s.startswith(prefix [,start [,end]]) , - prefix.
s.strip([chrs]) , chrs.
s.swapcase() , .
s.title() , - - .
s.translate(table [,deletechars]) - table, - ,
deletechars.
s.upper() .
s.zfill(width) - width.
xrange()
xrange([i,]j [,stride]) , - k, i
72 3.
, , ( , ).
m[k], k . , KeyError. len(m) , . - , , . 3.6.
3.6. ,
len(m) m.
m[k] m k.
m[k]=x m[k] x.
del m[k] m[k].
k in m True, k m.
m.clear() m.
m.copy() m.
m.fromkeys(s [,value]) , - s, - value.
m.get(k [,v]) m[k], , - v.
m.has_key(k) True, m k, - False. ( - in. Python 2.)
m.items() (key, value).
m.keys() .
m.pop(k [,default]) m[k], , ; default, , KeyError.
m.popitem() (key, value) - .
m.setdefault(k [, v]) m[k], , - v m[k] = v.
m.update(b) b m.
m.values() m.
73
, . 3.6, - . m.clear() . m.update(b) (key,value), b. m.get(k [,v]) - v, . m.setdefault(k [,v]) m.get(), , v - , m[k] = v. v , None. m.pop() . m.popitem() - .
m.copy() - . m.fromkeys(s [,value]) - , s. , m. - None, value . - fromkeys() , , , : dict.fromkeys().
m.items() , (key, value). m.keys() , m.values() . . Python 2 , Python 3 - , . - , Python. , . , items = list(m.items()). , keys = list(m).
. , . , . , , . : set - , frozenset . - :
s = set([1,5,10,15])
f = frozenset([a,37,hello])
, set() frozenset(), , - , . - , . 3.7.
74 3.
3.7. ,
len(s) s.
s.copy() s.
s.difference(t) . s, t.
s.intersection(t) . , s t.
s.isdisjoint(t) True, s t - .
s.issubset(t) True, s - t.
s.issuperset(t) True, s - t.
s.symmetric_difference(t) . , s t, .
s.union(t) . , s t.
s.difference(t), s.intersection(t), s.symmetric_difference(t) s.union(t) . - , s (set frozenset). t Python, . , , . - , 4.
( set) , . 3.8.
3.8. ,
s.add(item) item s. , .
s.clear() s.
s.difference_update(t) s, - t.
s.discard(item) item s. -, .
s.intersection_update(t) s t s.
s.pop() s.
75
s.remove(item) item s. item - , KeyError.
s.symmetric_difference_
update(t)
s t s.
s.update(t) t s. t , , .
s. t - , .
, Python , -Python , - , - , . . 3.9 - , - .
3.9. Python
types.BuiltinFunctionType
type
object
types.FunctionType
types.MethodType
types.ModuleType
object
type
, . 3.9 object type , - , , .
, , . , , , - , .
76 3.
, def lambda. :
def foo(x,y):
return x + y
bar = lambda x,y: x + y
f :
f.__doc__
f.__name__
f.__dict__ ,
f.__code__ -
f.__defaults__
f.__globals__ ,
f.__closure__ , ,
Python 2 , func_code, func_defaults . - Python 2.6 Python 3.
, . : , - :
class Foo(object):
def instance_method(self,arg):
@classmethod
def class_method(cls,arg):
@staticmethod
def static_method(arg):
, . , - self. - , . - cls. ,
77
. - , .
types.MethodType. , , , , - (.). (.) , . , - . f.instance_method(arg) Foo :
f = Foo() #
meth = f.instance_method # ()
meth(37) #
meth . - , () . - (self). meth -, , , - () .
- . :
umeth = Foo.instance_method # instance_method Foo
umeth(f,37) # self
umeth . , , , - . f Foo. , TypeError. :
>>> umeth(hello,5)
Traceback (most recent call last):
File , line 1, in
TypeError: descriptor instance_method requires a Foo object but received a str
(:
( ):
, 1,
TypeError: instance_method Foo,
str
)
>>>
- types.MethodType, - . :
78 3.
m.__doc__
m.__name__
m.__class__ ,
m.__func__ ,
m.__self__ , (None )
Python 3 , -Python 3 , - 3 , - types.MethodType. - Foo.instance_method, , , , . , Python 3 self.
, C C++, types.BuiltinFunctionType. - :
b.__doc__
b.__name__ /
b.__self__ , ( )
, len(), __self__ - None, , - . , x.append, x , __self__ x.
, -. class . - __init__() - . , __call__(). x, x(args) x.__call__(args).
79
, , type. :
>>> class Foo(object):
... pass
...
>>> type(Foo)
t type, - :
t.__doc__
t.__name__
t.__bases__
t.__dict__ ,
t.__module__ ,
t.__abstractmethods__ ( , )
, , - . :
>>> f = Foo()
>>> type(f)
i:
i.__class__ ,
i.__dict__ ,
__dict__ , - , - , - , - , - , - , - , - , -, -, -- . , i.attr = value, value . , __slots__, - , __dict__. Python 7.
80 3.
, , - import. , import foo, foo . - , , __dict__. , - ( ), - . , m.x -- m.__dict__[x]. , : m.x = y, m.__dict__[x] = y. :
m.__dict__ ,
m.__doc__
m.__name__
m.__file__ ,
m.__path__ . , -
, , - . -, , , , Ellipsis. . 3.10. , .
3.10.
types.CodeType -
types.FrameType
types.GeneratorType
types.TracebackType
slice
Ellipsis
81
, - , -, compile(). , , , , , - . c - , :
c.co_name
c.co_argcount ( )
c.co_nlocals , -
c.co_varnames
c.co_cellvars , -
c.co_freevars . ,
c.co_code -
c.co_consts , -
c.co_names , -
c.co_filename ,
c.co_firstlineno
c.co_lnotab , -
c.co_stacksize ( )
c.co_flags , -. 2 (0x04) , - (*args). 3 (0x08) , (**kwds). -
- -
82 3.
( ). f , :
f.f_back ( )
f.f_code
f.f_locals ,
f.f_globals ,
f.f_builtins ,
f.f_lineno
f.f_lasti . - f_code
( - ):
f.f_trace , -
f.f_exc_type ( Python 2)
f.f_exc_value ( Python 2)
f.f_exc_traceback - ( Python 2)
- . sys.exc_info(). , :
t.tb_next , - ( , - )
t.tb_frame ,
t.tb_lineno ,
t.tb_lasti ( ), -
83
- (- 6 -). - , - yield. -. :
g.gi_code -
g.gi_frame -
g.gi_running , -
g.next() -, yield, ( Python 3 __next__())
g.send(value) value . yield -. - -, yield. send() - , - yield
g.close() , - GeneratorExit -. ,
g.throw(exc [,exc_value [,exc_tb ]]) - yield. exc , exc_value exc_tb - -. , , yield
, - , : a[i:j:stride], a[i:j, n:m]
84 3.
a[..., i:j]. slice([i,] j [,stride]). , :
s.start . None, .
s.stop . None, .
s.step . None, .
s.indices(length). (start,stop,stride) . :
s = slice(10,20) # [10:20]
s.indices(100) # (10,20,1) > [10:20]
s.indices(15) # (10,15,1) > [10:15]
Ellipsis Ellipsis (ellipsis) []. , El-lipsis. , True. Ellipsis Python, , -Python, , -, , - [] - . , Ellipsis :
class Example(object):
def __getitem__(self,index):
print(index)
e = Example()
e[3, ..., 4] # e.__getitem__((3, Ellipsis, 4))
Python , . , -, , , , -, s[n], len(s) . . - - (__). - . , x + y x.__add__(y), x[k] x.__getitem__(k).
85
, .
, - , , -. , - ( ) - , .
, .
, . 3.11, , -, . 3.11, , - . 3.11, , - . 3.11, , - . 3.11, , - . 3.11, , -. 3.11, , -. 3.11, , -3.11, , - . __new__() , . __init__() - . __del__() . , . , del x - . 7.
3.11.
__new__(cls [,*args [,**kwargs]]) .
__init__(self [,*args [,**kwargs]])
__del__(self)
__new__() __init__() - . A(args), - :
x = A.__new__(A,args)
is isinstance(x,A): x.__init__(args)
__new__() __del__(). __new__() - , ( , , ). __del__() , - , - .
86 3.
. 3.12 , .
3.12.
__format__(self, format_spec) -
__repr__(self)
__str__(self)
__repr__() __str__() . __repr__() , - - eval(). , - . - repr(). repr() eval():
a = [2,3,4,5] #
s = repr(a) # s = [2, 3, 4, 5]
b = eval(s) #
- - , , __repr__() , :
f = open(foo)
a = repr(f) # a =
__str__() str(), -, . __repr__() , - . __repr__().
__format__() format() format(). format_spec , - . , format(), , format_spec format(). -:
format(x,spec) # x.__format__(spec)
x is {0:spec}.format(x) # x.__format__(spec)
87
- . -, 4.
. 3.13 , - . 3.13 , -. 3.13 , -. 3.13 , -3.13 , - . __bool__() True False. , - __len__(). __hash__() , . -, . , ; - , - .
3.13.
__bool__(self) False True
__hash__(self) -
- (, =, ==, !=). - , Boolean, Python. , , , - . , . , , . 3.14.
3.14. ,
__lt__(self,other) self < other
__le__(self,other) self other
__ge__(self,other) self >= other
__eq__(self,other) self == other
__ne__(self,other) self != other
88 3.
- , . 3.14. -3.14. - -, == - , __eq__(). , - , min() max(), -, , __lt__().
. 3.15 , - , - isinstance() b issubclass(). - , 7.
3.15.
__instancecheck__(cls,object) isinstance(object, cls)
__subclasscheck__(cls, sub) issubclass(sub, cls)
. 3.16 , /- . 3.16 , /-. 3.16 , /-. 3.16 , /-3.16 , /- (.) del .
3.16.
__getattribute__(self,name) self.name.
__getattr__(self, name) self.name, , AttributeError.
__setattr__(self, name, value) - self.name = value. - , - .
__delattr__(self, name) self.name.
__getattribute__() , - . , . __get-attr__(). __getattr__() Attrib-uteError. __setattr__(), __delattr__().
89
- , - , , . - , , - . 3.17. , .
3.17. -
__get__(self,instance,cls) - AttributeError
__set__(self,instance,value) value
__delete__(self,instance)
__get__(), __set__() __delete__() __getattribute__(), __setattr__() __delattr__() . - . - . - . - . - . - . -. -. - - , - . , , . - -, , -, . 7.
. 3.18 , , - .
3.18.
__len__(self) self
__getitem__(self, key) self[key]
__setitem__(self, key, value) self[key] = value
__delitem__(self, key) self[key]
__contains__(self, obj) True, obj self; False
90 3.
:
a = [1,2,3,4,5,6]
len(a) # a.__len__()
x = a[2] # x = a.__getitem__(2)
a[1] = 7 # a.__setitem__(1,7)
del a[2] # a.__delitem__(2)
5 in a # a.__contains__(5)
__len__() len() - . , __bool__() - .
- __getitem__(), , key. Python, . __setitem__() - - - - - - -- value . __delitem__() , del . __contains__() in.
, __getitem__(), __setitem__() __deli-deli-tem__() , x = s[i:j]. - - slice. , - . :
a = [1,2,3,4,5,6]
x = a[1:5] # x = a.__getitem__(slice(1,5,None))
a[1:3] = [10,11,12] # a.__setitem__(slice(1,3,None), [10,11,12])
del a[1:4] # a.__delitem__(slice(1,4,None))
, Python, -Python, -, - , . , - , , :
a = m[0:100:10] # (=10)
b = m[1:10, 3:20] #
c = m[0:100:10, 50:75:5] #
m[0:5, 5:10] = n #
del m[:10, 15:] #
i:j[:stride], stride () . , - . , - (- ...) :
91
a = m[..., 10:20] #
m[10:20, ...] = n
, __get-get-item__(), __setitem__() __delitem__() . - , - Ellipsis. ,
a = m[0:10, 0:100:5, ...]
__getitem__():
a = m.__getitem__((slice(0,10,None), slice(0,100,5), Ellipsis))
, Python -Python - - , - 4. Python, , - .
obj , obj.__iter__(), . iter, , iter.next() ( iter.__next__() Python 3), -Python 3), - 3), - StopIteration . - for , - . , for x in s :
_iter = s.__iter__()
while 1:
try:
x = _iter.next() # _iter.__next__() Python 3
except StopIteration:
break
# , for
...
. 3.19 , - . 3.19 , -. 3.19 , -. 3.19 , -3.19 , - . , , 4; , x + y, - x.__add__(y). , - r, , - . , . , x, x + y, __add__(), y.__radd__(x).
92 3.
3.19.
__add__(self,other) self + other
__sub__(self,other) self - other
__mul__(self,other) self * other
__div__(self,other) self / other ( Python 2)
__truediv__(self,other) self / other (Python 3)
__floordiv__(self,other) self // other
__mod__(self,other) self % other
__divmod__(self,other) divmod(self,other)
__pow__(self,other [,modulo]) self ** other, pow(self, other, modulo)
__lshift__(self,other) self > other
__and__(self,other) self & other
__or__(self,other) self | other
__xor__(self,other) self ^ other
__radd__(self,other) other + self
__rsub__(self,other) other - self
__rmul__(self,other) other * self
__rdiv__(self,other) other / self ( Python 2)
__rtruediv__(self,other) other / self (Python 3)
__rfloordiv__(self,other) other // self
__rmod__(self,other) other % self
__rdivmod__(self,other) divmod(other,self)
__rpow__(self,other) other ** self
__rlshift__(self,other) other > self
__rand__(self,other) other & self
__ror__(self,other) other | self
__rxor__(self,other) other ^ self
__iadd__(self,other) self += other
__isub__(self,other) self -= other
__imul__(self,other) self *= other
__idiv__(self,other) self /= other ( Python 2)
__itruediv__(self,other) self /= other (Python 3)
93
__ifloordiv__(self,other) self //= other
__imod__(self,other) self %= other
__ipow__(self,other) self **= other
__iand__(self,other) self &= other
__ior__(self,other) self |= other
__ixor__(self,other) self ^= other
__ilshift__(self,other) self = other
__neg__(self) self
__pos__(self) +self
__abs__(self) abs(self)
__invert__(self) ~self
__int__(self) int(self)
__long__(self) long(self) ( Python 2)
__float__(self) float(self)
__complex__(self) complex(self)
__iadd__(), __isub__() . . - , , a+=b a-=b ( -). - - - . , self , , .
, __div__(), __truediv__() __floordiv__(), (/) - (//). , Python 2.2, Python 3 /, . Python 2 / - __div__(). . Python 3 / __truediv__() - . Python 2 , -Python 2 , - 2 , - from __future__ import division.
__int__(), __long__(), __float__() __complex__() -, -
94 3.
. , int() float(). - . , - 3 + x TypeError, x __int__() .
, __call__(self [,*args [, **kwargs]]). x , , . x(arg1, arg2, ...) x.__call__(self, arg1, arg2, ...). , , -. :
class DistanceFrom(object):
def __init__(self,origin):
self.origin = origin
def __call__(self, x):
return abs(x - self.origin)
nums = [1, 37, 42, 101, 13, 9, -20]
nums.sort(key=DistanceFrom(10)) # 10
DistanceFrom, - . , sort(), - .
with , . :
with context [ as var]:
, context , . 3.20. __enter__() with. , , , as var. __exit__() -, , - with. __exit__() , -, - . None.
95
3.20.
__enter__(self) . , as with.
__exit__(self, type, value, tb) , - . - , type, value tb - , - . with -, , . - , . 5 -.
dir() dir() . , dir(), __dir__(self). - , . , , __dict__ .
4.
, Python. -Python. -. - , - - .
, - :
x + y
x y
x * y
x / y
x // y
x ** y (xy)
x % y (x mod y)
-x
+x
(//, , ) -, . Python 2 (/) , . 7/4 1, 1.75. - Python 3 ,
97
. x // y. , 7 % 4 3. x // y, - x (x // y) * y. (%) (//) .
, :
x > y
x & y
x | y
x ^ y
~x
, , -. , , . , Python , - .
, :
abs(x)
divmod(x,y) (x // y, x % y)
pow(x,y [,modulo]) (x ** y) % modulo
round(x,[n]) 10-n ( )
abs() . divmod() , . pow() **, ( -( - - -- ). round() x , 10 n. n , 0. x , Python 2
98 4.
, (, 0.5 1.0, -0.5 -1.0). Python 3, , - (, 0.5 0.0, 1.5 2.0). Python 3.
- True, -, False, :
x < y
x > y
x == y
x != y
x >= y
x z, - , , ( , x z ). - , , TypeError.
, - . - :
1. , .
2. , .
3. - .
, - , . -, , - .
99
, - , , :
s + r
s * n, n * s n s, n
v1,v2, vn = s
s[i]
s[i:j]
s[i:j:stride]
x in s, x not in s
for x in s:
all(s) True, s ,
any(s) True, - s ,
len(s)
min(s) s
max(s) s
sum(s [, initial])
+ . - s * n n . - - , . :
>>> a = [3,4,5]
>>> b = [a]
>>> c = 4*b
>>> c[[3, 4, 5], [3, 4, 5], [3, 4, 5], [3, 4, 5]]
>>> a[0] = -7
>>> c[[-7, 4, 5], [-7, 4, 5], [-7, 4, 5], [-7, 4, 5]]
>>>
, c. a - b. b - . , -
100 4.
a . - -. , , a. :
a = [ 3, 4, 5 ]
c = [list(a) for j in range(4)] # list()
, copy .
-. :
items = [ 3, 4, 5 ]
x,y,z = items # x = 3, y = 4, z = 5
letters = abc
x,y,z = letters # x = a, y = b, z = c
datetime = ((5, 19, 2008), (10, 30, am))
(month,day,year),(hour,minute,am_pm) = datetime
- -. , - . , -, 3 , . - -, , -.
s[n] n- -, s[0] . , - , - . , s[-1] . , -, IndexError.
s[i:j] , , k i
101
, s[i:j:stride], . - - - - - - - - - -- . stride, i j, - s[i], s[i+stride], s[i+2*stride] , j ( ). stride - - - - - - - - --. i, - , , . j, - , stride , stride . :
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[::2] # b = [0, 2, 4, 6, 8 ]
c = a[::-2] # c = [9, 7, 5, 3, 1 ]
d = a[0:5:2] # d = [0,2]
e = a[5:0:-2] # e = [5,3,1]
f = a[:5:1] # f = [0,1,2,3,4]
g = a[:5:-1] # g = [9,8,7,6]
h = a[5::1] # h = [5,6,7,8,9]
i = a[5::-1] # i = [5,4,3,2,1,0]
j = a[5:0:-1] # j = [5,4,3,2,1]
x in s x s True False. x not in s - x s. in not in . , hello in hello world True. , in - . , - , re.
for x in s - 5 - . len(s) - . min(s) max(s) - ; , < (, ). sum(s) - s, . - . . , sum(items, decimal.Decimal(0)) - Decimal ( decimal - 14 ).
102 4.
- . - :
s[i] = x
s[i:j] = r
s[i:j:stride] = r
del s[i]
del s[i:j]
del s[i:j:stride]
s[i] = x i, - x x. - , , -, IndexError. - s[i:j] = r k, i
103
. , . , . a b, - , a < b.
. - , - ( ASCII ). , . , , . , - ( - unicodedata locale).
, . Python : . , , , . - (, + == ). - Python 3 TypeError, Python 2 . Py-Py-thon 2 - 2 - . , , - .
(s % d) , s , d (). sprintf() C. : ( ) , . d , - d. d , - ( - , ).
104 4.
% -, . 4.1.
4.1.
d, i .
u .
o .
x .
X ( - ).
f [-]m.dddddd.
e [-]m.ddddddexx.
E [-]m.ddddddExx.
g, G %e %E, -4 ; -
%f.
s . - str().
r , repr().
c .
% %.
% - :
1. , - . , - KeyError.
2. :
-, . .
+, ( ).
0, .
3. , . , , ( , ) .
4. , .
5. , - ; ,
105
, , .
, (*). , - .
:
a = 42
b = 13.142783
c = hello
d = {x:13, y:1.54321, z:world}
e = 5628398123741234
r = a is %d % a # r = a is 42
r = %10d %f % (a,b) # r = 42 13.142783
r = %+010d %E % (a,b) # r = +000000042 1.314278E+01
r = %(x)-10d %(y)0.3g % d # r = 13 1.54
r = %0.4s %s % (c, d[z]) # r = hell world
r = %*.*f % (5,3,b) # r = 13.143
r = e = %d % e # r = e = 5628398123741234
% , , - ( $var ). -, , - , :
stock = {
name : GOOG,
shares : 100,
price : 490.10 }
r = %(shares)d %(name)s %(price)0.2f % stock
# r = 100 GOOG 490.10
, - . vars() , - , .
name =
age = 41
r = %(name)s, %(age)s % vars()
s.format(*args, **kwargs) . - - s. {n}, n , - format(). {name}
106 4.
. - {, {{, }} }. :
r = {0} {1} {2}.format(GOOG,100,490.10)
r = {name} {shares} {price}.format(name=GOOG,shares=100,price=490.10)
r = , {0}, {age} .format(,age=47)
r = {{ }} .format()
- . , {name[n]}, n , n- - name, {name[key]}, key , name[key]. {name.attr} - name.attr. :
stock = { name : GOOG,
shares : 100,
price : 490.10 }
r = {0[name]} {0[shares]} {0[price]}.format(stock)
x = 3 + 4j
r = {0.real} {0.imag}.format(x)
- . , - .
- . -, (:), : {place:format_spec}. - , -. :
r = {name:8} {shares:8d} {price:8.2f}.format
(name=GOOG,shares=100,price=490.10)
[[fill[align]][sign][0][width][.precision][type], , [], -. width , - align , , . - fill , . :
name = Elwood
r = {0:10}.format(name) # r = Elwood
r = {0:^10}.format(name) # r = Elwood
r = {0:=^10}.format(name) # r = ==Elwood==
type . . 4.2 - . type ,
107
s, d f.
4.2.
d, i .
b .
o .
x .
X ( - ).
f, F [-]m.dddddd.
e [-]m.ddddddexx.
E [-]m.ddddddExx.
g, G e E, -4 ; - f.
n , g, - .
% 100 f, %.
s . str().
c .
sign - +, - . + , - . - , . , . precision -. width 0, - . :
x = 42
r = {0:10d}.format(x) # r = 42
r = {0:10x}.format(x) # r = 2a
r = {0:10b}.format(x) # r = 101010
r = {0:010b}.format(x) # r = 0000101010
y = 3.1415926
r = {0:10.2f}.format(y) # r = 3.14
r = {0:10.2e}.format(y) # r = 3.14e+00
108 4.
r = {0:+10.2f}.format(y) # r = +3.14
r = {0:+010.2f}.format(y) # r = +000003.14
r = {0:+10.2%}.format(y) # r = +314.16%
- , format(). . :
y = 3.1415926
r = {0:{width}.{precision}f}.format(y,width=10,precision=3)
r = {0:{1}.{2}f}.format(y,10,3)
- . , .
, - . format() __format__(self, format_spec) . format() . , , - -.
- , str() repr(), , __format__(). !s !r. :
name =
r = {0