Бизли Д. - python. Подробный справочник (4-е изд.) - 2010

858

Upload: serega-borovsky

Post on 10-Aug-2015

321 views

Category:

Documents


0 download

TRANSCRIPT

PythonEssential ReferenceFourth 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 translation is published 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 .......................................... 211. ........................................................... 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 ........................................ 25712. ........................................................ 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. ............................................... 73126. 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), . , , .

, , . , , , , . , , . , , , - , , . , , . , . . : : [email protected] Mark Taber Associate Publisher Pearson Education 800 East 96th Street Indianapolis, IN 46240 USA

- informit.com/register, , .

Python. . Python , . , Python Python. , Python , C Java. , . (, ) . Python http://www.python.org. , UNIX, Windows Macintosh. , - Python , . Python. Python. . Python 2.6 Python 3.0. Python 3 . : Python 3.0 Python 2.x, ? , C, . , - , , , . , . , Python 2, Python 3. Python 3, (, ). , , Python .

20

Python. , .1 Python ; . , - , , , , , . , Python, . , . , . , , Python . , . , . -, Python . , , . , . , , Python . Python, , , . . (David Beazley) , , 2009

1

. Python. . . . : , 2000. . .

I 1. 2. 3. 4. 5. 6. 7. 8. 9. - ,

.

Python

10. 11. , ,

1

.

Python. , Python, . , , , , , , , , . . . , . Python Python 3, , Python 2.6. , Python 3 , , . Python 3.

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, , Python 3. - , , print Python 3 . , . :>>> print(, ) , >>>

Python 2, , . Python. , , , , Python 2 Python 3.

Python . . , , Python . :>>> 6000 + 4523.50 + 134.12 10657.620000000001 >>> _ + 8192.32 18849.940000000002 >>>

Python _, . . , . , , , :# helloworld.py print ,

25

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 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

- else: has_spam = False

29

, < >, True False. in, , , , . True False, , :has_spam = spam in s

- :f = open(foo.txt) line = f.readline() while line: print line, # print(line,end=) line = f.readline() f.close() # # readline() # , # Python 3

open() . , . readline() , . . 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], :

a = , b = a[4] # b =

31

, 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

append():names.append(Paula)

insert():names.insert(2, Thomas)

:b = names[0:2] c = names[2:] names[1] = Jeff names[0:2] = [Dave,Mark,Jeff] # # # # # [Jeff, Mark] [Thomas, Ann, Phil, Paula] 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]

, :

a[1] # Dave a[3][2] # 9 a[3][3][1] # 101

33

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. . . 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)

34address = (www.python.org, 80) person = (first_name, last_name, phone)

1.

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 = []

for line in open(filename): fields = line.split(,) # name = fields[0] # shares = int(fields[1]) price = float(fields[2]) stock = (name,shares,price) portfolio.append(stock)

35

# (name, shares, price) #

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 b c d = = = = t t t t | & ^ s s s s # # # # # t s t s (, 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

, , Python, . , , , . , , . , , , . , :

prices = { GOOG AAPL IBM MSFT }

37

: : : :

490.10, 123.50, 91.50, 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. . , , . :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]. , :

38for n in range(1,10): print 2 %d = %d % (n, 2**n)

1.

range(i,j [,stride]) , i j-1. , . stride . :a b c d = = = = range(5) range(1,8) range(0,14,3) range(8,1,-1) # # # # a b c d = = = = 0,1,2,3,4 1,2,3,4,5,6,7 0,3,6,9,12 8,7,6,5,4,3,2

range() Python 2, . . 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 = remainder(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:

40count = 0 ... def foo(): global count count += 1

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) #

42if matchtext in line: print line

1.

, , (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. . , def. -

44

1.

. self. , , self. , , . , __init__() . :s = Stack() s.push(Dave) s.push(42) s.push([3,4,5]) x = s.pop() y = s.pop() del s # #

# x [3,4,5] # y 42 # 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

(: ( ): foo.py, 12, IOError: [Errno 2] : file.txt )

45

, . . 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

, :

from div import *

47

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 . -, help() Python. . help() help(_), . help() , . 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 ... ( . .). ) >>>

, Python pydoc, Python. pydoc topic .

2

.

, Python. , , , , , .

. , (\), :a = math.cos(3 * (x - n)) + \ math.sin(3 * (y - n))

, , . , (...), [... ], {...} , , . , , , . , . :if a: 1 # 2

else: 3 4 # ()

49

, , , , :if a: 1 else: 2

pass. :if a: pass else:

, . Python ( ) . Python , , , 8 (, 11, 16). Python -t, , , . -tt, TabError. , (;). , , , . # , . , # , . , , . .

, , , , . - (_), .

50

2.

AZ az ISO-Latin. Z Z z z -Latin. Latin. . , FOO foo . , $, % @. , , if, else for . :and as assert break class continue def del elif else except exec finally for from global if import in is lambda nonlocal not or pass print raise return try while with yield

, , . , , , _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.1 () \ \a \b \e \0 \n \v \t \r \f \OOO \uxxxx \Uxxxxxxxx \N{ } \xhh

2.

( \000 \377) ( \u0000 \uffff) ( \U00000000 \Uffffffff) ( \x00 \xff)

\OOO \x , ( , , , ). , . , Jalapeo, , Jalape\xf1o, \xf1 . Python 2 8- . . Python 2 . , , u . :s = uJalape\u00f1o

Python 3 ( ), . Python 2 , -U ( , u ).

53

Python \u, \U \N . 2.1 . , U+XXXX, XXXX . ( : 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. , Python 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 :+ ^ -= ~ *= * < /= ** > //= / = **= % == &= > ^= & += >>= | print fact._ _doc__ >>>

, . , . .

, , , , , . @ , , . :

56class Foo(object): @staticmethod def bar(): pass

2.

, . :@foo @bar def spam(): pass

6 7 - .

Python 7- ASCII. , , , . Python , , :#!/usr/bin/env python # -*- coding: UTF-8 -*

s = Jalapeo # UTF-8.

coding: , , . 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, , . 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)

if isinstance(d,dict): d.update(t)

59

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>>> sys.getrefcount(a) 7 >>>

3.

, . , , , . , . , . :a = { } b = { } a[b] = b b[a] = a del a del b

# a b # b a

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) >>> b is a False >>> b.append(100) >>> b [1, 2, [3, 4], 100] >>> a [1, 2, [3, 4]] >>> b[2] [0] = -100 >>> b [1, 2, [-100, 4], 100] >>> a [1, 2, [-100, 4]] >>> # a.

# b.

# , a # b

# , a

a b , , , . a b. , . Python , . copy.deepcopy(), :>>> >>> >>> >>> >>> [1, >>> [1, >>> import copy a = [1, 2, [3, 4]] b = copy.deepcopy(a) b[2] [0] = -100 b 2, [-100, 4]] a # , a 2, [3, 4]]

Python . , , , . , , -

62

3.

, , . , , :items = { number : 42 text : Hello World }

, . :items[func] = abs import math items[mod] = math items[error] = ValueError nums = [1,2,3,4] items[append] = nums.append # abs() # # #

, , . , . :>>> items[func](-45) # 45 >>> items[mod].sqrt(4) # 2.0 >>> try: ... x = int(a lot) ... except items[error] as e: # ... print(Couldnt convert) ... Couldnt convert >>> items[append](100) # >>> nums [1, 2, 3, 4, 100] >>> abs(-45) math.sqrt(4)

except ValueError as e

nums.append(100)

, 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 , . , . 3.1. , , isinstance(). Python 2, ( Python 3 ). 3.1. None type(None) int long float complex bool str unicode list tuple xrange None. ( Python 2) (True False) ( Python 2) , xrange() ( Python 3 range) dict set frozenset

None None (, ). Python , None. , . None , , . None False.

64

3.

Python : , , , . , . . : True False. True False 1 0 . 2147483648 2147483647 ( ). ( ). , , Python (, Python 3 ). , , , , . . Python 2 isinstance(x, int) False, x . Python (64 ). , IEEE 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.2. , s[i] s[i:j] s[i:j:stride] len(s) min(s) max(s) i- s s s s

66 3.2 () sum(s [,initial]) all(s) any(s)

3.

s , s, True , 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 ValueError, . s.extend(t) s, t. s.sort() . . , . , , . s.reverse() . , sort() reverse(), None.

67

3.4. list(s) s.append(x) s.extend(t) s.count(x) s.index(x [,start [,stop]]) s . x s. t s. x s. i, s[i] == x. start stop

, .s.insert(i,x) s.pop([i]) x i. i- . i , . s x . s . s. key , . reverse . key reverse .

s.remove(x) s.reverse() s.sort([key [, reverse]])

Python 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 . :

>>> a = {0} {age} >>> a.format(, age=40) 40 >>>

69

{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 , . sub. ( ). ( ). , suffix. . sub -1. s. sub . , - . , . , . , . , .

s.count(sub [,start [,end]]) s.decode([encoding [,errors]]) s.encode([encoding [,errors]]) s.endswith(suffix [,start [,end]]) s.expandtabs([tabsize]) s.find(sub [, start [,end]]) s.format(*args, **kwargs) s.index(sub [, start [,end]]) s.isalnum() s.isalpha() s.isdigit() s.islower() s.isspace()

70 3.5 () s.istitle() s.isupper() s.join(t)

3.

, . , . , t, s . s width. . , chrs. - sep. (head,sep,tail) (s, ,), sep s. old new. . . s width. - sep, . , , - sep. maxsplit . maxsplit , split(). , chrs. - sep. maxsplit . . keepnds 1, .

s.ljust(width [, fill]) s.lower() s.lstrip([chrs])

s.partition(sep)

s.replace(old, new [,maxreplace]) s.rfind(sub [,start [,end]]) s.rindex(sub [,start [,end]]) s.rjust(width [, fill]) s.rpartition(sep) s.rsplit([sep [,maxsplit]])

s.rstrip([chrs]) s.split([sep [,maxsplit]])

s.splitlines([keepends])

s.startswith(prefix [,start [,end]]) s.strip([chrs]) , prefix.

71

, chrs. , . , . table, , deletechars. . width.

s.swapcase() s.title()

s.translate(table [,deletechars])

s.upper() s.zfill(width)

xrange() xrange([i,]j [,stride]) , k, i >> 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 m.__doc__ m.__name__ m.__class__ m.__func__ m.__self__

3.

, , , (None )

Python 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 ( ) , , . , - , - , - , , ( ) , . 2 (0x04) , (*args). 3 (0x08) , (**kwds).

c.co_code c.co_consts c.co_names c.co_filename c.co_firstlineno c.co_lnotab c.co_stacksize c.co_flags

-

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 f.f_exc_value f.f_exc_traceback , ( Python 2) ( Python 2) ( 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__()) value . yield -. - , yield. send() , yield , GeneratorExit -. , yield. exc , exc_value exc_tb . , , yield

g.send(value)

g.close()

g.throw(exc [,exc_value [,exc_tb ]])

, , : a[i:j:stride], a[i:j, n:m]

84

3.

a[..., i:j]. slice([i,] j [,stride]). , : s.start s.stop s.step . None, . . None, . . 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) []. , Ellipsis. , True. Ellipsis 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, , , . . __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 , . . __bool__() True False. , __len__(). __hash__() , . , . , ; , . 3.13. __bool__(self) __hash__(self) False True -

(, =, ==, !=). , Boolean, Python. , , , . , . , , . 3.14. 3.14. , __lt__(self,other) __le__(self,other) __gt__(self,other) __ge__(self,other) __eq__(self,other) __ne__(self,other) self < other self other self >= other self == other self != other

88

3.

, . 3.14. , == , __eq__(). , , min() max(), , , __lt__().

. 3.15 , , isinstance() b issubclass(). , 7. 3.15. __instancecheck__(cls,object) __subclasscheck__(cls, sub) isinstance(object, cls) issubclass(sub, cls)

. 3.16 , /. (.) del . 3.16. __getattribute__(self,name) __getattr__(self, name) self.name. self.name, , AttributeError. self.name = value. , . self.name.

__setattr__(self, name, value)

__delattr__(self, name)

__getattribute__() , . , . __getattr__(). __getattr__() AttributeError. __ setattr__(), __delattr__().

89

, , , . , , . 3.17. , . 3.17. - __get__(self,instance,cls) __set__(self,instance,value) __delete__(self,instance) AttributeError value

__get__(), __set__() __delete__() __getattribute__(), __setattr__() __delattr__() . . , . , , . - , , , . 7.

. 3.18 , , . 3.18. __len__(self) __getitem__(self, key) __setitem__(self, key, value) __delitem__(self, key) __contains__(self, obj) self self[key] self[key] = value self[key] True, obj self; False

90:a = [1,2,3,4,5,6] len(a) x = a[2] a[1] = 7 del a[2] 5 in a # # # # # a.__len__() x = a.__getitem__(2) a.__setitem__(1,7) a.__delitem__(2) a.__contains__(5)

3.

__len__() len() . , __bool__() . __getitem__(), , key. Python, . __setitem__() value . __delitem__() , del . __contains__() in. , __getitem__(), __setitem__() __delidelitem__() , 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, , , . , , , :a = m[0:100: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:] # # # # # (=10)

i:j[:stride], stride () . , . , ( ...) :

a = m[..., 10:20] # m[10:20, ...] = n

91

, __getgetitem__(), __setitem__() __delitem__() . , Ellipsis. , a = m[0:10, 0:100:5, ...]

__getitem__():a = m.__getitem__((slice(0,10,None), slice(0,100,5), Ellipsis))

, Python , 4. Python, , .

obj , obj.__iter__(), . iter, , iter.next() ( iter.__next__() Python 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 , . . , , 4; , x + y, x.__add__(y). , r, , . , . , x, x + y, __add__(), y.__radd__(x).

92

3.

3.19. __add__(self,other) __sub__(self,other) __mul__(self,other) __div__(self,other) __truediv__(self,other) __floordiv__(self,other) __mod__(self,other) __divmod__(self,other) __pow__(self,other [,modulo]) __lshift__(self,other) __rshift__(self,other) __and__(self,other) __or__(self,other) __xor__(self,other) __radd__(self,other) __rsub__(self,other) __rmul__(self,other) __rdiv__(self,other) __rtruediv__(self,other) __rfloordiv__(self,other) __rmod__(self,other) __rdivmod__(self,other) __rpow__(self,other) __rlshift__(self,other) __rrshift__(self,other) __rand__(self,other) __ror__(self,other) __rxor__(self,other) __iadd__(self,other) __isub__(self,other) __imul__(self,other) __idiv__(self,other) __itruediv__(self,other) self + other self - other self * other self / other ( Python 2) self / other (Python 3) self // other self % other divmod(self,other) self ** other, pow(self, other, modulo) self > other self & other self | other self ^ other other + self other - self other * self other / self ( Python 2) other / self (Python 3) other // self other % self divmod(other,self) other ** self other > self other & self other | self other ^ self self += other self -= other self *= other self /= other ( Python 2) self /= other (Python 3)

__ifloordiv__(self,other) __imod__(self,other) __ipow__(self,other) __iand__(self,other) __ior__(self,other) __ixor__(self,other) __ilshift__(self,other) __irshift__(self,other) __neg__(self) __pos__(self) __abs__(self) __invert__(self) __int__(self) __long__(self) __float__(self) __complex__(self) self //= other self %= other self **= other self &= other self |= other self ^= other self = other self +self abs(self) ~self int(self) long(self) ( Python 2) float(self) complex(self)

93

__iadd__(), __isub__() . . , , a+=b a-=b ( ). . , self , , . , __div__(), __truediv__() __floordiv__(), (/) (//). , Python 2.2, Python 3 /, . Python 2 / __div__(). . Python 3 / __truediv__() . Python 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. , . , type, value tb , . with , , . , . 5 .

__exit__(self, type, value, tb)

dir() dir() . , dir(), __dir__(self). , . , , __dict__ .

4

.

, Python. . , .

, : x + y x y x * y x / y x // y x ** y x % y -x +x (xy) (x mod y)

(//, , ) , . 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) pow(x,y [,modulo]) round(x,[n]) (x // y, x % y) (x ** y) % modulo 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 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) any(s) len(s) min(s) max(s) sum(s [, initial]) n s, n True, s , True, s , s s

+ . 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 = y x y x = x y x & y x ^ y x | y x < y, x y, x >= y, x == y, x != y, x is y, x is not y x in s, x not in s not x x and y x or y lambda args: expr , ( ) , , , , , ,

, . 4.3, x y. , , , .

, . :if a 0: display() decrement()

nonlocal , ( ). , Perl, , nonlocal , local Perl. , , UnboundLocalError. , :i = 0 def foo(): i = i + 1 print(i)

# UnboundLocalError

i ( global). i = i + 1 i , . i, . , . , , i i + 1 i; i print(i) i, .

Python . , , . , :# foo.py def callf(func): return func()

, :>>> import foo >>> def helloworld(): ... return , ! ... >>> foo.callf(helloworld) #

, ! >>>

137

, , , . foo.py, :# foo.py x = 42 def callf(func): return func()

:>>> import foo >>> x = 37 >>> def helloworld(): ... return , ! x = %d % x ... >>> foo.callf(helloworld) # , ! x = 37 >>>

, helloworld() x, , helloworld(). x foo.py helloworld(), helloworld() x. , , , , . __globals__, , . , . __globals__ :>>> helloworld.__globals__ {__builtins__: , helloworld: , x: 37, __name__: __main__, __doc__: None foo: } >>>

, , . :import foo def bar(): x = 13 def helloworld(): return , ! x = %d % x foo.callf(helloworld) # , ! x = 13

138

6.

, , . :from urllib import urlopen # from urllib.request import urlopen (Python 3) def page(url): def get(): return urlopen(url).read() return get

page() . get(), -. , get(), , get(). :>>> python = page(http://www.python.org) >>> jython = page(http://www.jython.org) >>> python >>> jython >>> pydata = python() # http://www.python.org >>> jydata = jython() # http://www.jython.org >>>

, python jython, , get(). page(), , , get() get(). get() urlopen(url) url, page(). python jython, , . :>>> python.__closure__ (,) >>> python.__closure__[0].cell_contents http://www.python.org >>> jython.__closure__[0].cell_contents http://www.jython.org >>>

. , , :def countdown(n): def next(): nonlocal n r = n n -= 1 return r return next

# next = countdown(10) while True: v = next() # if not v: break

139

n . next() . , , , :class Countdown(object): def __init__(self,n): self.n = n def next(self): r = self.n self.n -= 1 return r

# c = Countdown(10) while True: v = c.next() # if not v: break

, , , , ( 50%). , , , . .

, , . . @ , :@trace def square(x): return x*x

:def square(x): return x*x square = trace(square)

140

6.

square(). trace(), square. trace, , :enable_tracing = True if enable_tracing: debug_log = open(debug.log,w)

def trace(func): if enable_tracing: def callf(*args,**kwargs): debug_log.write( %s: %s, %s\n % (func.__name__, args, kwargs)) r = func(*args,**kwargs) debug_log.write(%s %s\n % (func.__name, r)) return r return callf else: return func

trace() -, . , square(), debug.log write() -. callf, trace(), , . , enable_ tracing. False, trace() , - . , , . , . , . :@foo @bar @spam def grok(x): pass

. , :def grok(x): pass grok = foo(bar(spam(grok)))

, . :@eventhandler(BUTTON) def handle_button(msg): ...

yield@eventhandler(RESET) def handle_reset(msg): ...

141

:def handle_button(msg): ... temp = eventhandler(BUTTON) # handle_button = temp(handle_button) # ,

@ . , . :# event_handlers = { } def eventhandler(event): def register_function(f): event_handlers[event] = f return f return register_function

. :@foo class Bar(object): def __init__(self,x): self.x = x def spam(self):

-, , . , , , : Bar.spam. , - foo() . , , . .

yield yield, , . , . :def countdown(n): print( , %d % n) while n > 0: yield n n -= 1 return

142

6.

, , . :>>> c = countdown(10) >>>

. -, , , next() ( __next__(), Python 3). :>>> c.next() # Python 3 c.__next__() , 10 10 >>> c.next() 9

next() - , yield. yield , , next(). , , yield. , next() , for, sum() . :for n in countdown(10): a = sum(countdown(10))

- , StopIteration. , None. - , , , . , :for n in countdown(10): if n == 2: break statements

for break, . - close(), , . , close(). close(), , :>>> c = countdown(10) >>> c.next() , 10 10

yield>>> c.next() 9 >>> c.close() >>> c.next() Traceback (most recent call last): File , line 1, in StopIteration >>>

143

close() -, yield, GeneratorExit. .def countdown(n): print( , %d % n) try: while n > 0: yield n n = n - 1 except GeneratorExit: print( %d % n)

GeneratorExit, - yield. , , , close() .

yield yield , . :def receiver(): print( ) while True: n = (yield) print( %s % n)

, yield , . . :>>> r = receiver() >>> r.next() # yield (r.__next__() Python 3) >>> r.send(1) 1 >>> r.send(2) 2 >>> r.send() >>>

144

6.

next() , , yield. , send() - r. , send(), (yield) . , yield. , next() . , .def coroutine(func): def start(*args,**kwargs): g = func(*args,**kwargs) g.next() return g return start

:@coroutine def receiver(): print( ) while True: n = (yield) print( %s % n)

# r = receiver() r.send(, !) # : .next()

, . close(), :>>> r.close() >>> r.send(4) Traceback (most recent call last): File , line 1, in StopIteration

, StopIteration. close() GeneratorExit , . :def receiver(): print( ) try: while True: n = (yield) print( %s % n)

yieldexcept GeneratorExit: print( )

145

throw(exctype [, value [, tb]]), exctype , value tb . :>>> r.throw(RuntimeError, !) Traceback (most recent call last): File , line 1, in File , line 4, in receiver RuntimeError: !

, yield . . throw(), , . , yield, yield . :def line_splitter(delimiter=None): print( ) result = None while True: line = (yield result) result = line.split(delimiter)

, . send() . :>>> s = line_splitter(,) >>> s.next() >>> s.send(A,B,C) [A, B, C ] >>> s.send(100,200,300) [100, 200, 300] >>>

, , . next() (yield result), None result. send() line , result. , send(), , yield. , , send(), yield, , , send(). -

146

6.

- , , throw(). throw(), , yield , throw(). , .

, . , . , - , , UNIX. . 1 . , -, , , :import os import fnmatch

def find_files(topdir, pattern): for path, dirname, filelist in os.walk(topdir): for name in filelist: if fnmatch.fnmatch(name, pattern): yield os.path.join(path,name)

import gzip, bz2 def opener(filenames): for name in filenames: if name.endswith(.gz): f = gzip.open(name) elif name.endswith(.bz2): f = bz2.BZ2File(name) else: f = open(name) yield f

def cat(filelist): for f in filelist: for line in f: yield line

def grep(pattern, lines): for line in lines: if pattern in line: yield line

:wwwlogs files lines pylines = = = = find(www,access-log*) opener(wwwlogs) cat(files) grep(python, lines)

for line in pylines: sys.stdout.write(line)

147

, , access-log*, , www. accesslog , , . , python. for . . , , , - . , . , , . , for -, . , , :import os import fnmatch

@coroutine def find_files(target): while True: topdir, pattern = (yield) for path, dirname, filelist in os.walk(topdir): for name in filelist: if fnmatch.fnmatch(name,pattern): target.send(os.path.join(path,name))

import gzip, bz2 @coroutine def opener(target): while True: name = (yield) if name.endswith(.gz): f = gzip.open(name) elif name.endswith(.bz2): f = bz2.BZ2File(name) else: f = open(name) target.send(f)

@coroutine def cat(target): while True: f = (yield) for line in f: target.send(line)

@coroutine def grep(pattern, target):

148

6. while True: line = (yield) if pattern in line: target.send(line)

@coroutine def printer(): while True: line = (yield) sys.stdout.write(line)

, , :finder = find_files(opener(cat(grep(python,printer()))))

# finder.send((www,access-log*)) finder.send((otherwww,access-log*))

, target. , find_files(). , , . , close(). , , , send(), . . , , . , , , , . 20 .

, . :nums = [1, 2, 3, 4, 5] squares = [] for n in nums: squares.append(n * n)

, , . :

nums = [1, 2, 3, 4, 5] squares = [n * n for n in nums]

149

:[expression for item1 in iterable1 if condition1 for item2 in iterable2 if condition2 ... for itemN in iterableN if conditionN ]

:s = [] for item1 in iterable1: if condition1: for item2 in iterable2: if condition2: ... for itemN in iterableN: if conditionN: s.append(expression)

:a = [-3,5,2,-10,7,8] b = abc

c = [2*s for s in a] # c = [-6,10,4,-20,14,16] d = [s for s in a if s >= 0] # d = [5,2,7,8] e = [(x,y) for x in a # e = [(5,a),(5,b),(5,c), for y in b # (2,a),(2,b),(2,c), if x > 0 ] # (7,a),(7,b),(7,c), # (8,a),(8,b),(8,c)]

f = [(1,2), (3,4), (5,6)] g = [math.sqrt(x*x+y*y) for x,y in f]

# f = [2.23606, 5.0, 7.81024]

, , , for, . . if ; , . , . , : [(x,y) for x in a for y in b], : [x,y for x in a for y in b]. , , Python 2 , , . , x, [x for x in a], , , ,

150

6.

. , Python 3, .

-- , , , . - , , . :(expression for item1 in iterable1 if condition1 for item2 in iterable2 if condition2 ... for itemN in iterableN if conditionN)

, - . , . :>>> a = [1, 2, 3, 4] >>> b = (10*i for i in a) >>> b >>> b.next() 10 >>> b.next() 20 ...

- , . , , - , . . :# f = open(data.txt) # lines = (t.strip() for t in f) # # comments = (t for t in lines if t[0] == #) # for c in comments: print(c)

-, , . , . , for, -

151

. . , . Python . , - , . , (, append()). - list():clist = list(comments)

- , . () . , [x*x for x in a if x > 0] { x2 | x a, x > 0 }. , , , , . , , portportfolio.txt, , .txt, txt, , , :AA 100 32.20 IBM 50 91.10 CAT 150 83.44 MSFT 200 51.23 GE 95 40.37 MSFT 50 65.10 IBM 100 70.44

, , , :lines = open(portfolio.txt) fields = (line.split() for line in lines) print(sum(float(f[1]) * float(f[2]) for f in fields))

. , . , , , , :total = 0 for line in open(portfolio.txt): fields = line.split()

152

6. total += float(fields[1]) * float(fields[2]) print(total)

, UNIX. , , -, awk:% awk { total += $2 * $3} END { print total } portfolio.txt 44671.2 %

, - select SQL, . , , , :fields = (line.split() for line in open(portfolio.txt)) portfolio = [ {name : f[0], shares : int(f[1]), price : float(f[2]) } for f in fields]

# msft = [s for s in portfolio if s[name] == MSFT] large_holdings = [s for s in portfolio if s[shares]*s[price] >= 10000]

, ( 17), . :sum(shares*cost for shares,cost in cursor.execute(select shares, cost from portfolio) if shares*cost >= 10000)

lambda lambda , :lambda args : expression

args , , expression , . :a = lambda x,y : x+y r = a(2,3) # r 5

lambda . lambda , , for while. lambda- , .

153

lambda- , . , :names.sort(key=lambda n: n.lower())

. :def factorial(n): if n > factorial(6) 120 >>> if n >> help(factorial) Help on function call in module __main__: ( call __main__:)

call(*args, **kwargs) (END) >>>

155

, . :def wrap(func): call(*args,**kwargs): return func(*args,**kwargs) call.__doc__ = func.__doc__ call.__name__ = func.__name__ return call

functools wraps, . , :from functools import wraps def wrap(func): @wraps(func) call(*args,**kwargs): return func(*args,**kwargs) return call

@wraps(func), functools, func .

. :def foo():

foo.secure = 1 foo.private = 1

, __dict__ . , , . , . , . , , .

156

6.

, functools.wraps(), :def wrap(func): call(*args,**kwargs): return func(*args,**kwargs) call.__doc__ = func.__doc__ call.__name__ = func.__name__ call.__dict__.update(func.__dict__) return call

eval(), exec() compile() eval(str [,globals [,locals]]) str . :a = eval(3*math.sin(3.5+x) + 7.2)

exec(str [, globals [, locals]]) str, Python. . , exec(). :a = [3, 5, 10, 13] exec(for i in a: print(i))

, Python 2 exec() . exec, , : exec for i in a: print i. - Python 2.6, Python 3. exec(). ( , ). , eval() exec() , . :globals = {x: 7, y: 10, birds: [Parrot, Swallow, Albatross] } locals = { }

# , , , # a = eval(3 * x + 4 * y, globals, locals) exec(for b in birds: print(b), globals, locals)

, . , - -

eval(), exec() compile()

157

, , exec() SyntaxError, lambda-. exec() eval() -. , , , . compile(str,filename,kind) -, str , , filename , ( ). kind : single , exec eval . , compile(), eval() exec(). :s = for i in range(0,10): print(i) c = compile(s,,exec) # exec(c) #

s2 = 3 * x + 4 * y c2 = compile(s2, , eval) # result = eval(c2) #

7

.

- . , - . , , C Java. ( 3 .)

class , , , . (, ), (, ) (, ). class. , . :class Account(object): num_accounts = 0 def __init__(self,name,balance): self.name = name self.balance = balance Account.num_accounts += 1 def __del__(self): Account.num_accounts -= 1 def deposit(self,amt): self.balance = self.balance + amt

def withdraw(self,amt): self.balance = self.balance - amt def inquiry(self): return self.balance

159

, , , , . , , Account:Account.num_accounts Account.__init__ Account.__del__ Account.deposit Account.withdraw Account.inquiry

, class (, Accounts). , , . . , , . , , . self, . deposit(), withdraw() inquiry(), , . , num_accounts, , ( ). Account.

, . , __init__() . , __init__(), : self , . :# a = Account(, 1000.00) # Account.__init__(a,,1000.00) b = Account(, 10.00)

__init__() self. , self.name = name name . , , , (.), :

160

7. - a.deposit(100.00) # Account.deposit(a,100.00) b.withdraw(50.00) # Account.withdraw(b,50.00) name = a.name #

(.) . . , a.name name a. a.deposit deposit () Account. , , . .

, , . . , self. self.balance, balance. , :class Foo(object): def bar(self): print(bar!) def spam(self): bar(self) # ! bar NameError self.bar() # Foo.bar(self) #

, Python C++ Java. , , , self Python , this. self , Python , , , int x float y C. , , . self , self, , .

, . . -

161

. , . . class . object, . object , Python , __str__(), print. . , Account, inquiry(), , , , :import random class EvilAccount(Account): def inquiry(self): if random.randint(0,4) == 1: return self.balance * 1.10 # : else: return self.balance

c = EvilAccount(, 1000.00) c.deposit(10.0) # Account.deposit(c,10.0) available = c.inquiry() # EvilAccount.inquiry(c)

EvilAccount Account, inquiry(). Python (.). , , . , . , c.deposit() deposit(), Account. , __init__(). , EvilAccount evilfactor:class EvilAccount(Account): def __init__(self,name,balance,evilfactor): Account.__init__(self,name,balance) # # Account self.evilfactor = evilfactor def inquiry(self): if random.randint(0,4) == 1:

162

7. - return self.balance * self.evilfactor else: return self.balance

__init__(), __init__() . , __init__(). , Account.__init__(). __init__(), . , __init__(), , , . , . , self , :class MoreEvilAccount(EvilAccount): def deposit(self,amount): self.withdraw(5.00) # EvilAccount.deposit(self,amount) #

, EvilAccount deposit(). Account. , , , (, EvilAccount deposit()). , super(), :class MoreEvilAccount(EvilAccount): def deposit(self,amount): self.withdraw(5.00) # super(MoreEvilAccount,self).deposit(amount)#

super(cls, instance) , . , . ( , , ). , super() . Python 3 super().deposit(amount), , . Python 2 . Python . . :

class DepositCharge(object): fee = 5.00 def deposit_fee(self): self.withdraw(self.fee)

163

class WithdrawCharge(object): fee = 2.50 def withdraw_fee(self): self.withdraw(self.fee)

# , class MostEvilAccount(EvilAccount, DepositCharge, WithdrawCharge): def deposit(self,amt): self.deposit_fee() super(MostEvilAccount,self).deposit(amt) def withdraw(self,amt): self.withdraw_fee() super(MostEvilAcount,self).withdraw(amt)

, . :d = MostEvilAccount(Dave,500.00,1.10) d.deposit_fee() # DepositCharge.deposit_fee(). fee == 5.00 d.withdraw_fee() # WithdrawCharge.withdraw_fee(). fee == 5.00 ??

deposit_fee() withdraw_fee() . , withdraw_fee() , fee, . , fee , . , ? (: DepositCharge.fee.) , , . , , , . EvilAccount , Account, Account. MostEvilAccount, DepositCharge , WithdrawCharge, . , __mro__ . :>>> MostEvilAccount.__mro__ (, , , , ,

164

7. - ) >>>

. , , , . - , - -. C3-, A Monotonic Superclass Linearization for Dylan ( A Dylan) ( . (K. Barrett) , OOPSLA96). 96). , Python TypeError. :class X(object): pass class Y(X): pass class Z(X,Y): pass # TypeError. # #

Z, . , X Y, . Y , X. X, Y, X. , , , . , . -. , , , , ( ). , , - . DepositCharge WithdrawCharge, . , deposit_fee(), , . , , DepositCharge. ( , ).

,

165

: fee, deposit_fee() withdraw_ fee() , , self (, DepositChange.fee).

, (, , ) . , . , , obj.attr, attr , , . , . , obj. obj.name obj, name. ( : , , , , ). Python, . , , , , . . , , , , . , , . , .

, , , , self. , . , , . . @staticmethod, :

166

7. - class Foo(object): @staticmethod def add(x,y): return x + y

, . - . :x = Foo.add(3,4) # x = 7

. __init__(), , :class Date(object): def __init__(self,year,month,day): self.year = year self.month = month self.day = day @staticmethod def now(): t = time.localtime() return Date(t.tm_year, t.tm_mon, t.tm_day) @staticmethod def tomorrow(): t = time.localtime(time.time()+86400) return Date(t.tm_year, t.tm_mon, t.tm_day)

# a b c

= Date(1967, 4, 9) = Date.now() # now() = Date.tomorrow() # tomorrow()

, . @classmethod. , , cls, . :class Times(object): factor = 1 @classmethod def mul(cls,x): return cls.factor*x

class TwoTimes(Times): factor = 2

x = TwoTimes.mul(4) # Times.mul(TwoTimes, 4) -> 8

, TwoTimes mul() . , , , .

167

, , , Date, , :class EuroDate(Date): # , # def __str__(self): return %02d/%02d/%4d % (self.day, self.month, self.year)

Date, . now() tomorrow() . , EuroDate.now(), EuroDate Date. , :class Date(object): ... @classmethod def now(cls): t = time.localtime() # return cls(t.tm_year, t.tm_month, t.tm_day)

class EuroDate(Date): ...

a = Date.now() # Date.now(Date) Date b = EuroDate.now() # Date.now(EuroDate) EuroDate

, , . . :a = Date(1967,4,9) b = a.now() # Date.now(Date)

, a.now() a. Python, - , Smalltalk Ruby. .

, . , . :class Circle(object): def __init__(self,radius): self.radius = radius # Circles

168

7. - @property def area(self): return math.pi*self.radius**2 @property def perimeter(self): return 2*math.pi*self.radius

Circle :>>> c = Circle(4.0) >>> c.radius 4.0 >>> c.area 50.26548245743669 >>> c.perimeter 25.132741228718345 >>> c.area = 2 Traceback (most recent call last): File , line 1, in AttributeError: cant set attribute (: ( ): , 1, AttributeError: ) >>>

Circle c.radius, , c.area c.perimeter, . @property , , , (), , . , , , , ( AttributeError ). (Uniform Access Principle). , , . , , c.radius, , c.area(). , (), , . . Python , , .