Вы находитесь на странице: 1из 702

Python 3 .

PyQt

2012

681.3.06
32.973.26-018.2
84

. .

84

Python 3 PyQt. .--:- .:


2012.-704 .: .-

-,

ISBN 978-5-9775-0797-4

Python:

, , ,

, , , -
, ,

SQLite,

PyQt,
Python. n ,
, Qt Designer,

, (,
, , , , .)
. .

681.3.06
32.973.26-018.2

ni

01.12.11.

70100 1 / 16 . . . . . 56,76.

1200

Nv 1349

"-'', 190005, -, ., 29.


-

Nv 77.99.60.953..5770.05.09 26.05.2009 .
.

" ""
-, 9 ,

199034,

ISBN 978-5-9775-0797-4

12

. .,

2012

, "-",

20 12'

..........................................................................................................................

1.

PYTHON 3 ................................................................................ 15

.................................................................................................. 17
Python .................................................................................................................... 17
1.2. n Python .................................................................................................. 23
1.3. n ............................................................................................................ 24
1.4. ........................................................................................................................... 27
1.1.

1.

13

1.~.

IDLE ................................................................................................. 28

1.6.
1.7.

1.8.

.......................................................................................................... 33

1.1.
2.2.
2.3.
2.4.
2.5.
2.6.

.................................................................................................... 36

....................................................................................................... 36

........................................................................................................................... 38

.................................................................................. .41

..................................................................................................... ,..... .43

3.

............................................................................................. .44
... :......................... :............................................................................. .47

......;............................................................................................... 48

................................................................................................... .48

.............................................................................................................. 50
................................................................. 51
....................................................................................................... 52
...................................................................................... 53

4.1.
4.2.
4.3.

2.

3.1.
3.2.
3.3.
3.4.
3.5.

................................................................................ 29

............................................................................................................................ 3 1

4.

................................................................... 55

............................................................................................................. 56

if .. e/se ........................................... ,....................................................... 58

................................................................................................................................... 61

4.4.
4.5.
4.6.
4.7.

5.1.
5.2.
5.3.

rangeO

enumerateO .............................................................................................. 63

whi/e ................................................................................................................................ 66
continue. ............................................ 67
break. ...................................................................................... 67

5.

................................................................................................................ 69

........................................................................ 70

6.

math. .............................................................................. 72
random. ...................................................................... 73

............................................................................................................ 76

6.1. ...................................................................................................................... 77
6.2. ........................................................................................................... 81
6.3. .......................................................................................................... 81
6.4. ........................................................................................................... 84
6.5. Meojormat0 ......................................................................................................................... 90
6.6. ......................................................................... 94
6.7. ................................................................................................................... 97
6.8. .............................................. ,................................................ 98
6.9. ........................................................................................ 98
6.1 Q. ....................................................................................................... 99
6.11. ................................................................................. 102
6.12. bytes ................................................................................................................. I05
6.13. bytearray ......................................................................................................... 108
6.14. .................................................. 112
6.15. ............................................................................................................. 112

7.1.
7.2.
7.3.
7.4.
7.5.

7.

............................................................................. 114

.................................................................................. :.. 114

..............................................................................

123

........................................ ,.......................................... 127


..................................................................................................................... 128
................................................................................................... 130

8. ....................................................................................... 132
8.1. ......... ;.......................................................................................................... 132
8.2. ....................................................................................................... 136
8.3. ........................................................................................................... 139
8.4. . ................................................................................................... 139
8.5. - .................................................................. 140
8.6. mapO, zipO,filterO reduceO ............................................................................... 141
8.7. .......................................................................... 144
8.8. ...................................................................................................... 147
8.9. ....................................................................... 148
8.1 . .............................................................................. 148
8.11. ...................................................................... ,....................................... 149
8.12. ............................................................................................... 150
8.13. ....................................................................................... 151
8.14. ............................................................................................................................... 151

8.15.

8.15.1.
8.15.2.
8.15.3.
8.15.4.

9.1.
9.2.
9.3.
9.4.
9.5.
9.6.
9.7.

9.

itertoo/s ................................................................................................................... l53

.............................................. 153
.......................................................................... 154
........................................................

156
..................................................................................................... 157

................................................................................. 159

..................................................................................................................

159
161
................................................................................................. 163
............... , ....................................................................... 164
............................................................................................................ 166
............................................................................................................................. 167
.......................................................................................................... 172

......................................................................................................

10.1.
10.2.
10.3.
10.4.

1.

.......................................................................

173

................................................................................. 173
...................................................................................... 175
"" .......................................................................................................... 177
datetime. .......................................................... 178
10.4.1. timedelta ........................................................................................................ 178
10.4.2. date ............................................ :................................................................... 180
10.4.3. time ............................................................................................... ................. 183
10.4.4. datetime ......................................................................................................... 184
10.5. ca/endar. .................................................................................. 189
10.5.1. TextCalendar LocaleTextCalendar........................................... l90
10.5.2. HTMLCalendar LocaleHTMLCalendar ................................... 191
10.5.3. ..................................................................................... 192
10.6. ......................................................... 195

11.

.................................................................... 197

11.1. ............................................................................................. 197


11.2. ............................................................................... 200
11.3. ............................................. ..20 1
11.4. ....................................................................... 203
11.5. .......................................................................................................... 205
11.6. - .......................................................................................................... 206
11. 7. .......................................................................................................... 207
11.8. . ................................................................................... 209
11.9. .............................................................................. 210
11.1 . ........................................................................................................ 213
11.11. ................ ...................................... :.................................................. 215

12.

....................................................................................... 216

12.1. import .............................................................................................................. 216


12.2. fr ................................................................................................................. 219
12.3. ......................................................................................................... 222
12.4. ............................................................................................. 223
12.5. ................................................................................................................................. 224

13. -11 ................................ 228

13.1. n n ......................................................... 228


13.2. _init_O _de/_0 ............................................................................................ 231
13.3. ...................................................................................................................... 232
13.4. ........................................................................................... 234
13.5. n .......................................................................................................... 236
13 .6. n ....................................................................................................... 239
13.7. .............................................................................. 242
13 .8. .......................................................................................................... 243
13.9. n ............................................... 244
13.1 . ................................................................................................................ 245
13 .11. ......................................................................................................... 246

14.

............................................................................ 247

14.1. try... except... e/se...final/y .. :........................................................................... 1.. 248


14.2. with... as ........................................................................................................... 252
14.3. ....................................................................................... 254
14.4. .......................................................................................... 256
15. ............................................................. 259

15.1. .................................................................................................................. 259


15.2. .......................................................................................... 265
15.3. n n os ........................................................................... 271
15.4. String/0 Bytes/0 .................................................................................................. 273
15.5. n ................................................................................ 277
15.6. .n ......................................................................... 278
15.7. n ..................................................................... 281
15.8. n ! ......................................................................................... 283
15.9. ............................................................................................. 286
15.1 . .................................................................................. 289

16. SQLite ........................................................................................... 293

16.1. ....................................................................................................... 293


16.2. ............................................................................................................... 295
16.3. n ................................................................ ; ................................................. 301
16.4. n ........ :............................................................................... 303
16.5. .............................................................................................. 304
16.6. n .................................................................................................................... 305
16.7. n ............................................................................... 308
16.8. WHERE .......................................................................................... 309
16.9. ............................................................................................................................... 312
16.1 . n ......................................................................................................... 314
16.11. ........................................................... : ............................................................ 315
16.12. ................................................................................... 317

17 .1.
17.2.
17.3.

17.

SQLite Python ................................................ 318

................................................................................... 319

n n ........................................................................................................... 319
n ........................................................................................... 324

17.4. ................................................................................................. 327


17.5. ........................................................................... 328
17.6. .................................................................................. 330
17.7. .......................................................................................... 331
17.8. .......................................................................................... 332
17.9. ............................................................................. 336
17.1 . .................................................................................................... 337

18.

............................................................... 340

18.1. URL-apeca ............................................................................................................. 340


18.2. ................................................................ 343
18.3. .................................................. 34 7
18.4. L- ..... :........................................................................................ 347
18.5. ................................................................................ 348
18.6. ur//ib.reques/ ........................................................... 354
18.7. ..................................................................................................... 357

11. . ....................................... 359

19.1.
19.2.
19.3.
19.4.
19.5.

19.

PyQt ..................................................................................... 361'

PyQt ................................................................................................................... 361


............................................................................................................... 364
........................................................................................................ 365
- .................................................................................................. 367
Qt Designer ......................................................... 371
19.5.1. ..................................................................................................... 371
19.5.2. ui- ............................................................................ :373
19.5.3. ui- - ..................................................................... 375
19.6. PyQt ....................................................................................................................... 377
19.7. PyQt ........................................................................................................... 377
19.8. ..................................................................... 379
19.9. ............................. :............................................................... 381
19.9.1. QThread. ........................................ , ................................. 381
19.9.2. ..... ;..................................... , ........................... 384
19.9.3. queue. ............................... :........................... 388
19.9.4. QMutex QMutexLocker ........................................................................... 391
19.10. ................................................................................................................. 395
19.11. .................................................................................................... 397

20.1.
20.2.
20.3.
20.4.
20.5.

20.

............................................................. 398

........................................................................................... 398

....... :..................................................................................................... 399


............................................................................ 40 1

...................................................................................... .403
....................................................................................... .406

20.5.1.
20.5.2.
20.5.3.

QPoint. ........................................................................ .407


QSize. ................................................... .408
QRect. ......................... .41

20.6. ......................................... .'.................................... .415


20.7. ..................................................................................... .416

20.8. ................................................................................................................. .417


20.9. ........................................................................................ .419
20.1 . ............................................................................................ .420
20.1 1. ................................................................ 421
20.12. .............................................................................. 422
20.13. ................................................................................................ .423
20.14. .......................................................................................... 424

21.1.
21.2.
21.3.
21.4.
21.5.
21.6.
21.7.
21.8.

21.

.............................................................. 426

.................................................................................. 426

................................................................................ 430
.................................................................................... .433
........................................................ 435
.......................................................................................... 438
.................................................................................................... 439
...................................................................................................... .442
..................................................................................................................... .445
21.8.1. .................................................................................... 445
21.8.2. ........................................................ .446
21.8.3. .......................................................................... .447
21.8.4. .......................................................................... .448
21.9. ......................................................................................................... .449
21.9.1. ........................................................................................ 449
21.9 .2. ................................................................ .451
21.9.3. .................................................. .454
21.1 . ................................................................................................................. .455
21.1 0.1. ................................................................ .455
21.1 0.2. ...................................................................................... .456
21.10.3. ...................................................................... 457
21.1 0.4. .................................................................................. 457
21.1 0.5. .......... ,............................................ 458
21.11. drag & drop .................................................................................................... 460
21.11.1. ........................................................................................ .460
21.11.2. QMimeData ................................................................................................ .462
21.11.3. ................................................................................................ .463
21.12. ................................................................................................ .465
21.13. ........................................................................................................ 465
21.14. .................................................................................................. .466

22.1.
22.2.
22.3.
22.4.
22.5.
22.6.
22.7.
22.8.
22.9.

22.

.................................... .468

....................................................................................... .468
.............................................................. .469
...................................................................................................... 472
................................................................................. 473
QStackedLayout QStackedWidge/ ....................................................................... .415
QSizePo/icy ............................................................................................................... .411
................................................................................. 478
................................................................................................................. .479
............................................................................................................ 480

22.1 .
22.11.
22.12.

.................................................................................................. .484
.................................................................................... .485
........................................................................................ 487

""

23.

............................................................................ 489

23.1. ....................: .......................................................................................................... .489


23.2. .............................................................................................................. 492
23.3. ................................................................................................................... .494
23.4. ....................................................................................................:........................... 494
23.5. .......................................................................................... .495
23.5.1. ................................................................................. 495
23.5.2. ........................... :................................................ .-............... 498
23.5.3. ....................................................................................................... 499
23.6. ......................................................................................... 500
23.6.1. ................................. ~ ............................................... 500
23.6.2. ' ...................................................................................... 502
23.6.3. ............................................................. 504
23.6.4. QTextDocumen/ ............................................................................................. 505
23.6.5. QTextCursor .................................................................................................. 508
23.7. .............................................................................................................. 511
23.8. .................................................................. 512
23.9. ......................................................................................... 514
23.10. ........................................................................................................................... 516
23.11. .................................................................................................. 517
23.12. ................................................................................................. 518
23.13. ........................................................................................................... 519
23.14. QDia/ ....................................................................................................................... 521
23.15. ............................................................................................................. 522

24.1.

24.

t ..................................................................................... 523

.................................................................................................... 523

24.1.1.
24.1.2.
24.1.3.
24.1.4.
24.2.
24.3.
24.4.

, .................................................... 523
............................................................................................... 524
.............................................................................. 526
................................................................................................................... 526

.............................. :................................................................ 526


................................................................................................................... 527
................................................................................................................................. 528
24.4.1. .......................................................................... 528

24.4.2. QStringListMode/ .......................................................................................... 529


24.4.3. QStandardltemModel .................................................................................... 530
24.4.4. QStandardltem .............................................................................................. 533
1
24.5. .................................................................................................................... 536
24.5.1. QAbstractltem View ....................................................................................... 536
24.5.2. ...................................................................................................... 539
24.5.3. ................................................................................................................... 540
24.5.4. ........................................................................................... 543
24.5.5. ......................................................... 545
24.6. .................................................................................. 547
24.7. ..................................................................................................... 549

10

25.1.

25.

..................................................................................... 551

................................................................................................... 551

QColor. ................................................................................................ 551


QPen. ................................................................................................... 555
25.1.3." QBrush. .............................................................................................. 556
25.1.4. QLine. ................................................................................................ 557
25.1.5. QPolygon. .......................................................................... 558
25.1.6. QFont. .............................................................................................. 560
25.2. QPainter .................................................................................................................... 562
25.2.1. ...................................................................................... 562
25.2.2. ........................................................................................................... 565
25.2.3. ............................................................................................... 566
25.2.4. ....................................................................... 567
25.2.5. ................................................................. 568
25.3. .................................................................................................... 569
25.3.1. QPixmap ........................................................................................................ 570
25.3.2. QBitmap ........................................................................................................ 572
25.3.3. Qlmage .......................................................................................................... 573
25.3.4. Qlcon ............................................................................................................. 576
25.1.1.
25.1.2.

26.

.................................................................................... 578

26.1. QGraphicsScene. ....... :.................................................................................... 578


26.1.1. ................................................................................ 579
26.1.2. ................................................... 579
26.1.3. ....................................................................... 580
26.1.4. ....................................................................................................... 581
26.1.5. ................................................................................... 582
26.1.6. ........................................................................ 582
26.1.7. ..................................................................................... 583
26.2. QGraphicsView. ................................... _. .......................................... 584
26.2.1. ................................................................. 584
26.2.2. ......................... 586
26.2.3. ....................................................................................................... 586
26.2.4. ....................................................................... 587
26.2.5. ....................................................................................................... 587
26.3. QGraphics/tem. .................................. 588
26.3.1. ............................................................................. 588
26.3.2. ........................................................................................ 590
26.3.3. ....................................................................................................... 591
26.4. ......................................................................................................... 592
26.4.1. ....................................................................................................................... 592
26.4.2. QAbstractGraphicsShapeltem ....................................................................... 593
26.4.3. ....................................................................................................... 593
26.4.4. ....................................................................................................... 593
26.4.5. ..................................................................................................................... 594
26.4.6. ........................................................................................................... 594
26.4.7. ......................................................................................................... 595
26.4.8. ........................................................................................ 595

11

26.5. nn ............................................................................................. :.......... 597


26.6. .............................................................................................................................. 597
26.6.1. QGraphicsE.ffect ............................................................................................ 597
26.6.2. ......................................................................................................................... 598
26.6.3. ................................................................................................................. 599
26.6.4. ..................................................................................................... 599
26.6.5. n .............. :........................................................................ 600
26.7. ............................................................................................................. 600
26.7.1. ................................................................................. :............ 600
26.7.2. ..................................................................... ,................................. 60\
26.7.3. n ..................................................................... 603
26.7.4. .............................................................................................. 605
26.7.5. ............................................................ 605

27.1.
27.2.
27.3.

27.

....................................................................................... 607

.................................................................................. 607

QDia/ogButtonBox .................................................................................................... 610


QMessageBox .... :............................................................................................... ;....... 612
27.3.1. ................................................................................. 614
27.3.2. ................................................................ 616
27.3.3. n ................................................................................ 616
27.3.4. n ............................................... 617
27.3.5. ......................................................... 617
27.3.6. " n" .............................................................................................. 618
27.3.7. "About Qt" ..................................................................................................... 618
27.4. QlnputDia/og ............................................................................................................. 618
27.4.1. ................................................................................. 619
27.4.2. ........................................................................................... 621
27.4.3. ................................................................................ 621
27.4.4. .................................................................. 622
27.4.5. n ....................................................................... 623
27.5. QFileDialog ............................................................................................................... 623
27.5.1. ................................................................................. 624
27.5.2. ..................................................................................... 626
27.5.3. ...................................................................................... 627
27.5.4. ................................................................................... 628
27.6. ....................................................................................................... 629
27.7. ................................................................................................... 630
27.8. ........................................................................... 631
27.9. n .................................................................................. 632
27.1 . ............................................................................. 633
27.1 0.1. QWizard .................................................................... :................................. 633
27.10.2. QWizardPage ............................................................................................... 637

28.1.
28.2.

28.

SDI-

DI- ......................................................... 640

n ................................................................................ 640
.................................................................................................................................... 644

28.2.1. QMenuBar ........................................................................................... :......... 645


28.2.2. QMenu ................................................................................. .'.......................... 646

12

28.2.3.
28.2.4.
28.2.5.

28.3.

28.4.
28.5.
28.6.

28.7.

.................................................................................................. 648

QAction ......................................................................................................... 649


rpynny ............................................................... 652
......................................................................................................... 653
28.3.1. QToo/Bar ....................................................................................................... 653
28.3.2. QToo/Button .................................................................................................. 655
n n ...................................................................................................... 656
n ......................................................................................... 658
DI-n ...... ,......................................................................................................... 659
28.6.1. QMdiArea ...................................................................................................... 659
28.6.2. QMdiSubWindow .......................................................................................... 662
n ............................................... 663
n

............................

v 665

. ................................................ 666

- 667

Python-

Python

PyQt!

, .

, , ,
W-, .

Python

, ,
.

Python 3.2

Windows.

(Guido van Rossum)


"Monty Python's Flying Circus".

"". ,

"". , .

Python

Python

( n)

pyw (

).

.
-
. , ,
-. ,

, , ,
.

Python

- . ,

, .

, . , ,
, .

Python

, , .

, -, ,
.

Python

-, .

'Python-

. ,

Perl

. ,

Perl,

14
.

Python

, . .

. ,

llttp://pytln.org/dcv/peps/pep-0008/.
.

Python

. , I

( begin ... end)


.

.
.
. . ,

- . .
J< .
.

Python

, ,
. , Pytho
.

r Python ,

Notepad++.

. , PyScripter, PythonWi, UliPad, Eclipse +


PyDev, Netbeas . llttp://
wiki.python.org/moin/PytlnEditors.

IDLE,

Pytho

PyQt,

Windows.

.

.

Qt Designer,

Designer

Qt

L-,

Python.

,
.

Python 3

1.

2.

3.

4.

5.

6.

7.

8.

9.

1 .

11.

12.

13.

14.

15.

16.

17.

18.

SQLite
SQLite

Pytho

, .
-, , ,
, , - .

, ,
. -, ,

. ! ,
. ,
. , ? Pytho ,
!

1.1.

Python

Pytho.

1.

python-3.2.msi.

http://python.org/download/

2.

(.

1.1)

3.

(.

1.2)

(C:\Pytho32\)

4.

lnstall for all users

Next.

(.

1.3)

Next.

pyw

5.

Next.

, .

Finish

1.4.

C:\Python32. : pytho.exe pythonw.exe.


python.exe .

pythow.exe .

pyw.

/. Python 3

18

~ Vy1110t\ 3. 2 S~tup

---

_ta

-- ....-.....;...-~-S-e-le-ct--whetlter to lnstall Pytlto .2 for

all users of thls compute~.

1j

~::: :~::: av~ ~ ~~ta) l


(not

python

(\)(

1-wiodows
_" __0000"

1
Next >

i'ld,
'"

-0 ""

. .-

. . .. -0000000

..

. ..

..

000

. .

---0

1.1. Python.

Select Oestination Oirectory

Please select di'ectorv fur the Pyttoo 3.2 files.


,-

"-

01

1 1 Cancel

J" ....

1d Pythoo32

--

-----=~

: python
1
1

f('lr

windows

t--~------1

]: \Python32\
0"_,.......:..__.....,..._ _ _ _ _ - -

--

[ N";xt >
.

1.2.

1 C<!ICel

Python. 2

python.exe, n
(. 1.5). > n Jt
Python. n ~, n, 2 + 2
<Enter>, n,

1.

19

n n . , n

, . t
n n

Python (command line) 1 1 Python 3.2.

jg/Pyth< 3.2Sttllp

Ej

------..-----_____..........---......---.= .

Customize Python 3.2

Select the. WaY you want features to mtalled.

CitX icons n the tree elow to chanae the


wav feat:ures WJI nstalled.

- .:" "[.el
13 ReQister Extensions

9 Tcl/11<
;; Doci.'Ielltation

9 utility ScriPtS
::::

Test stite

Python Tnter~et!!f and I.rar1es

python

Ttis f r~es 22!3 hatd drive.

has 5 of 5 sufeature> se\ected.

reQUi'e 2ere on hatd drive,

windows
1~ \J;$aQe J

f Advared }
.

1.3. Python.

python
((wr

GICk the. Flrlsh utton to eXIt the lflstaller.

windows

1.4.

Python.

lt

h stfeatures

20

1.5.

/.

Python

,
,

IDLE,

. n J<: 1 1 Python 3.2


IDLE (Python GUI). Python Shell (. 1.6),
,
, . '
.

IDLE

Pyt.hon
in32

~ . 2

(r32:88445,

"copyright.",

f~b

20 2011, 21 : 29 : 02)

"cr~d1t."

or

"l1cene()"

[ KSC v . lSOO 32 bit. (Int.e l )] on v

:tor

mor~

1n:tormat.ton.

>;>> 1

Python

1.6. Python Shell

IDLE

, , ,

Python 3 n Python 2.
3.2, n 2.7
3.2 .

2.5?

n . , ,
.
.

n.

3.1, !'.;l n
http://python.org/
http://www.activestate.com/activepython/


n ActiveState.
downloads/

ActiveState , . .
n Edit with Pythonwin. n PythonWin,
IDLE.
PythonWin, n.
no (C:\Python31 \). :
Custom Setup (. 1.7) n Register as Default Python
(. 1.8). , Python 3.2.
n

1.

21

Custom~tup

Selett the ~ want features to lnst*<!.

1 Disk~ 1

Reset

1.7. t< Custom Setup

Custom St=tuP

Activestate

Selett the WlJV wnt fe&ues to lnstlled.

~ lcons in tho tree elow to thonoe the "'" features wil onstoled.

ReQOSter tNs Pyt/-oon tnst~ es


the def~ Python (~ ., .
sociattons; 4dd to .;nd
; etc.)

' Thls feat..re re~es 8 cn '/fU

lwdd-ive.

ActivePython

1.8.

Reglster as Default Python

PythonWin

1<11

. n, n
,

IDLE31.bat. :

@echo off
start C:\Python31\pythonw.exe

C:\Pythonl\Lib\idlelib\idle.pyw

n
n

IDLE.
IDLE.

IDLE (Python GUI).

Python 3.2,

IDLE

Python 3. 1.
3.2

1 1 Python

22

/.

Python 3

r-t n Pytho .
Pytho 3.2.
. , n

. n n n

,

python.exe. , n

python31.exe nn C:\PythonI. n
, n . 1.9. .
n n n Python.

( 13

(}

~~?&:: Ic:~est
$r

--

Edit w.th IDI.E

Edt wlth Pythono.wt

~~~::::

)8

/ ") 11

~ fl

lq /i]

1_
Pro --..".-----, - -------.

! ~~ --~--~-.. ~1 ..
!l64 8 ...
1. - 11 >\8 "test.r"
8 <I1111 ~ no e-rnad. ..

; ~ "test.rar" fl /1<3 eIil

python

,;>

---- -------
_j

0f~<3!1

EJ .

pythonI
1 .",. python2S
i : ; nr;

t~

~ ..

~--------'

jj -- -~---------- ---...-------
8!:!d
r111011

j ---- ---- -:______________._,_,__ ----------3

epet1eti()83Tb

<

1.9.

n nr

Python

n test.py n ,
n . n
: ...................., ...................... , .....................,~~...........~. ................. .. . .....,, ., ..... ,..............................! ...............

~ 1.1. ~!f

1.1.

1'''''"' '''"'"'''"""''"''''""'''"'"''''......................................., .,.,....... , .............. .

:.. ...........................................;...................................:................... ~ .......................................;.................................................................................................,.............................~ ...........,j

impor t s ys
pri nt (tuple(sys.version_ i nfo) )
t ry :
# Python 2
raw_ input ()
except NameError:
input ()
# Python 3

1.

23

n n n .
n1

final

(3, 2 ,

final 1 , 0),

n ,

(3,

1, 2,

OJ , Register as Default Python.

Python 3.2.

1.2.

Python

,
", !". n1-t ,

Python ( 1.2).

[~~~~~:~:~~~:~:.~:~?..~~~:~~~~~~~~~::~~:~i.~.~?.~:~:::::~::~:::::::~::::::::~: : : :~::::.::~::~::::::::~::~:::::~::::::::::~:::~::: : : : :~~~:::~:~~::~::~:J


i

n n

rint(",

print()

!")

n n 1 1 Python

3.2 1 IDLE
(Python G UI). Py thon Shell, >
n . 1.2,
. <Enter>.

, .
n

1.3.

.... ...,...................................................................................................... .................,_,................................................ ..................................,..................

.."

"'''''' '''"''"'"' ''' '' ' ''"'''''' '""~

i 1.3. n nr Python She/1


~............... ;_j,,, ~....................... ~............. ........... ............................j,,..., ....................;,.....,.;j....................................... ......... ......... .............-

>>> # n n
>>> rint (", !"}
, !
>>>

.............................; ...................................... ;

print()


>>> , .

File ri New Window.


1.2, test.py,
File 1 Save As. UT F-8
(Byte Order Mark, ). UTF-8
Python 3. ,

# -*- coding :

<>

# - *- coding:

IDLE

1251

-*-

Windows- 1251 :

-*-

.
.
, ~
.

/. Python 3

24

n n n , n

Run 1 Run Module


<F5>. n n Python
Shell.
n. n n .
n

Windows.

, n . . n
,

input (),
<Enter> n .
, n 1.4.

t''''''"'''''''''"'"''''''''''""'' ' "!''''"'''''''""''''"''"''"'"' ' ''.,.'''""'"""''"'''" ' " " "''' ' "''"'""'''"''''"'''"-.''"''''''"'"'" "' "''''" '''' "'"''"''''"' '' '"''"''''""'""'.,.,,,,.,,,.,,,,.,,,,.,,:..oo"'''' ""'''"'t

~ 11r 1.4. n -n n ,~r

t .......~... ~.~.............~................,,.................................. .-, ..;.......{,,.................................................--........................;..~ ................................................................._.. ,,.....;.....:..1

# -*- coding: utf-8 -*print ( ", !")


input ()

#
#

.ID-!

<Enter>

input () ,
, n , n
. n , n

IDLE

11

Python 3 no Unicode.
Unicode n .
, < Windows no n
866, n UTF-8.

, n n
n

Edit with IDLE. n


Python n ,
pyw, n n , n Notepad++.
n n , , PyScripter.

1.3.

, n Python n
. n .
, , -

( 1.5).

r.

. . . . . . . . . . . . . . . . . . . . . . . . . . .. .,. . . . . . . . . . . . . . . . .. ,. . . . . . . . . . . . . . . . . . . . . . . ...,. . . . . . . . . . . . . . !

~;~~; 1:s: ~~~~ ~~;;;;~

~,,,,, ,,,., ,;..,. ,,, ,..,,,..,,... , , ..,>oo;,,,.,..,,,,.,,,,,;, ..,,,,,,.>.. ,,,,,;,,.. , .,.. ,,,.., , ,.,, ,, , ,,,.,, , .,.. , ........... , /ooo oOoo.,OoOo ooOo o. ooo"'''''''"'l''.,"''...."iOo oooO> . .... ,,.... , ...;,_,~00"'''\,A, , .. , , ,,, ..,, ..ooO..oooooOoooooOo oO'"'''"' ' ' ' ' ' " j

>>>

import sys

SyntaxError: unexpected indent


>>>
n import n r,~, n
.

25

1.

n n n n
. n n n

UNIX,

Pytho11:

#!/usr/bin/python
n n n n-:

#!/usr/local/bin/python
n n, n n

env:

#!/usr/bin/env python
n env n n n

Python

n n.

n n

Python

. , n, n

n
)

\n

Windows

n - \r (n

(n ). n

\n.

UNlX

n n

FTP

, \r . . n
n

FTP

( ASCII).

\r . n
n. n n Python n 755 ( -rwxr-xr-x).
(

Windows

n ) .

, nn,

Windows-1251

UTF-8.

# -*- coding: cpl251 -*

IDLE

n n

n . n n n
n n , n

1.6.

# -*- coding: utf-8 -*import encodings.aliases


arr = encodings.aliases.aliases
keys = list( arr.keys()
keys. sort ( )
for key in keys:
print("%s => %s"% (key, arr[key]))
n (n, ,
n.

Python

Perl

.)

n n, .
n,

Python

JavaScript,

. . ,
, n

1. 7).

26
:.......... ..f ... ........ , ......._ , , ................_ ~............, ,

" ......\ _

/.

Python 3

............ ........................................... ...... 1. . ............ . .... ............ ..................... .._.~................. , ....... ................... ...........~

f 1.7. n~ 1ia

; .......................... . .... . .......................t ........................................................ . . , .~. ......; ; ............. . .......- ........~............... ................... . ......._ . ................................... . ....... . ........... .........................

>>> = 5;
> print (z )
15

= 10;

11

Python

. ,
while i :

$i = 1;
while ($i<11)
echo $i . "\n";
$i++;

echo

" n";

Python rr - ( 1.8).

~:~~~~~:~::~:~~~::~:~~~~:~~~"~:~~~~~~~~~~~~i.~~:~~i.~~:: : : : :~:~ : ~:~: :: : : : : : ~: :~ : : :~:~: : : : : : : : ,: :.::: : : : : :.: . : ::: : : .: : : .~: :. ,:.:J


i

=1

while i <1 1:
print (i)
i += 1
p rint ( "

n")

n. i

Python i . , n

, .
. ,
.

print , I " " .


i, i

. Python I
I .

Python n n n

, . ,

for i in range (l, 11):


print(i)
' p r int ( " ")
:

for i i n range (l , 11): print(i)


print ( " n" )

1.

27

, n
n n:

\.

. ( ) n. :
=

15 + 20 \
+ 30

print

()

n . n, . .
. :

(15 + 20

+ 30)

print

()

n n , . . n
. n:

arr

[15, 20,
30]
print (arr)
=

arr =

15,

{"":

"":

20,

"z": 30}
print (arr)

1.4.

n n n, n n
. n ,
, . , n,

Python.

n .

#:
#

Python

n .

, n
n . , n n ", !":

print

(",

!")

print ()

n ~, n:

rint(", !")

n n,

print("#

")

Python

( n):

28

print (",

!")

/. Python 3

, , . .

.
. , . .
.
, .

1.5. IDLE

JDLE.

.
,

Python Shell

> r .

<Enter>.

( , ), -
.

<Enter>

.
,

<Enter>.

>>> for n in range(1, 3):


print (n)
1
2

>>>
", !"

Python Shell


>>>",
1

print ().

. , 1 n

<Enter>

!"

>>>
, . ,

>>>

rint(",

print ():

!")

>>>
,

Python Shell

,
. :

>>> 12 * 32
438

>>>

+ 54

29

1.

_(
). .
. :

> 125 * 3
375
>
+ 50
425
>
1 5
85.0
>

375 + 50
425 1 5

<trl>+<>.
, .
, ,

. <t>
<J.>. <Enter>,
. , .

( )

.
n n

<Ait>+</>.

n .
, , , ,
.
n n n
. , , n , ,

, n (n)
). n

Edit.

Paste

. n n
n-

<Ctri>+<C> (n)
Windows,

. n-, n

<Ctrl>+<V>

().

n , n .
n

n ,

<Ait>+<P>

<Ait>+<N>

IDLE

. (
n) . n
n n . n
, .

1.6.


n n

print ().

print ( [<>] [, sep= 1

[,

end= 1 \n 1 ]

[,

file=sys. stdout])

print () n n stdout.
n~ n

file nn , n .

n .

30

/.

Python 3

print
print

1")
2")

("
("

1
2

print ()

1",

print("Cpoa

"

2")

, . .

sep .

print("Cpoa1",

"2",

sep="")

.
,

end

1", " 2", end=" ")


print (" 3")
# : 1 2 3

print("Cpoa

print ()

. :

for n in range(1, 5):


print (n, end=" ")
print ()
print("o ")

1 2 3 4

for,

print (), .

, . Pytln

. ,
, . .
. ,
.
.

print () ,

1.

31

,
. -

'. . :

print ( """ 1
2
3""")
~J :

1
2
3

print ()

write () sys. stdout:

import sys
sys. stdout. wr i te ("")

sys

, i mport, sys,
write ( J . ,

\n:

import sys
sys. stdout. wr i te (" 1\n")
sys.stdout .write ( " 2")

1.7.

n .

[<>

Python 3

stdin.

input (),

= 1 input ( [ <> 1)

~ ,
, 11 (

1.9).

"'" '''MO"t"''"0' '' ''' ' ''' ' ' ''t''''0f''''"''C''' ' " ' '"'''"'' 0'10'''''''' ' 0' '111"'''''"'''011'""''''" ''"'"'' 00 0' "'''-"""""' ' 01''''""""'"'... '" '""( 0.. 00000 ' 0\..000 000~0"'""'""''""'..~ ' 0 ' 0 ' 0 0 "''''''''''''"'''''''00''''..' ' '00000000000.,.0..0000 ..0 ~

f n1 1.9, n input ()

.ii......................................................................................._,,,,.....................\........................................................................................................................................................................J

i -- coding: utf- 8 - *-

= input ( "
name.rstrip("\r")
print (",", name)
input ( " <Enter> I
n

")

n=

3.2.0

" )

3.2.0

i nput ()

Windows

\r. ,
3.2.1 .

rstrip().

, , n

test.py,

32

1.

Python 3

".

, n " :
",

<Enter>.

, n "

", ~

". , n input ().


, n

<Enter>.

n input () , n

<Ctri>+<Z>,

<Enter>

EOFError. n ,

. :

try:
s = inut(" : ")
print (s)
except EOFError:
print (" !<: EOFError")
try > EOFError, n n
except. n except n n
.

Python 2 n" : raw_ input () input ().


raw_)nput () n , input ()

n eval () n

Python 3 raw_ input () n input (), n


input () . n input () Python 2,

n ~;~ > eval () :

# -*- coding: utf-8 -*result = eval(input("Bee


print (":", resul t)
input ()

"))

#:

2 + 2
4

eval ()

. ,

n . n
n argv sys. n argv
, n

test.py

C:\book.

n .

1.1 .

# -*- coding: utf-8 -*irnport sys


arr = sys.argv[:]
for n in arr:
print(n)
n n n n n .

n . > : n n.

crnd

n . ,

1.

n . n

33
C:\book.

od

:\k

:
:\k>

n n :

C:\Python32\python.exe test.py -uNik -pl23


(test.py)

(-uNik

-\23) .

test.py
-uNik
-12 3

1.8. n

Python

n n

. ,
1 Python 3.2 1 Python

Manuals.

n 1

pydoc

(.

1.10).

Python 3.2 1 Module Docs,

n n

, n . n n ,
, n n

bro,vser

open

W-, ,

. ,

n .

pydoc
<Enter>, n
go to selected.

n -
n . n
W-.

. 1.10.

Python She\1

IDLE

pydoc

help(). n

i nput () :

> help(input)
:

Help on built -in function input in module builtins:


input ( ... J
input ( [prompt )) -> string
2.

1349

34

/.

Python 3

Read string from standard input. The trailing newline is stripped.


If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enaled. The prompt string, if given,
is printed without trailing newline before reading.
n

help () n
, . n n
. n, n builtins, n
, :

>>> import builtins


>>> help(builtins)
, ,
n n.
n .
n,

_doc_.
help () n n .
.

n n.

test.py:

# -*- coding: utf-8 -* n

def func():
"""
pass

"""

"""

n n :

# -*- coding: utf-8 -*import test


help(test)

test.py

n:

Help on module test:


N

test -

FUNCTIONS
func ()
n

FILE
c:\book\test.py
n n n

# -*- coding: utf-8 -*import test


print(test. doc
print(test.func. doc

test.py

_doc_:

1.

35

n:
n

_doc_ n help (). n n


no . input ():

> print ( input.

doc

n:

input( [prompt]) -> string


Read string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enaed. The prompt string, if given,
is printed without trailing newline before reading.
n

# -*- coding: utf-8 -*import test


print ( dir (test)

dir ():

test.

:
[

1
builtins
_package_ 1 ,

- cachedfunc 1 ]

doc

file

name

n n :

>>> import builtins


>>> dir(builtins)

dir ( J .

# -*- coding: utf-8 -*import test


print ( dir ()

'

test .

:
[

builtins

doc

name

__package_ 1 ,

test 1 ]

Python n . n

. n . 1:1
( n ) .
.

2.1.

, ,
, n . ,

' , . .
. , ,
n , n n
,

from module import *,

.
n n .
,
;"'" .........._ ..........,...

~-~

2.1.

..............................................r.................,.......................,_,"._.,_........................... ,....... ...", .....................,.... ,.......- -, .................._...__.. ..................................

r 2.1. n Cf!OB

;...........- ..- - ...........................- ....................................."..............................~... ....~...................o~t........................................... . ..... ; .......... .....................................................................................

>>> import keyword


>>> keyword . kwlist
False 1 None 1 True 1 and 1 as 1 assert 1 break 1 c lass 1
Continueol 0 def 0 , 0 del 0 , oelif 0 1 elseol 0 except 0 1 finallyol 0 fOr 0 1
fromo 1
global 1 ifo 1 import 1 ino, iso 1 lamdao 1 ononlocal 1
0
nOt 0 1 0r 0 1 pass 0 1 raise 0 1 return1 try 0 1 While 0 1 With 0 1 oyield 0 ]
[

.
, ,
(
~.. , . ...,,....... "t .... , ........~ ................... ,....................~~

2.2).
...........
\

''1...~''"'"'"""'"'''''''' '' ' '.'' '"'''''''''' ' '''"'"~\~ " . .. ..~'"''''"'''"' '''''''"'''""''"''''"'"' '" '.'''"'"'..~.. ..

tt~r 2.2. n. l)l::i :t111t

......... ~............................".................................~....................................................................................................... ~........,.....~.....~..................................................................................._,J

> help(abs)
Help on built-in function abs in module builtins:

2.

37

... )

s(

as(numer)

->

numer

Return the absolute value of the argument.

> help
> help

10

10

> help (abs)


Traceback (most recent call last) :
File "<pyshellti9>", line 1, in <modu1e>
help (abs)
TypeError: ' i nt' object is not callale

s .

help

help <)

1.

help ,

. .

. ,
.
, ,

str.

str

n
n .

IDLE

. ,

. , ,
. -

, 2.3.
:..,.............. ,....,..., .. " ..........,..,,,,..,,.,.1 ..'''' '' '' '''"~'',1,"1"t.."""''"'Y"'.~''>'-'"'"'''

... , ....~ .....,..,,,,,,~,,..........., ..~..,,,,".,,,., ,".,,,., ..._,,,,,,.,. .... , ... ........, . ,., "'!-'''" '" ~' ' "'''f'"'' ..''"''""''!

'''''"'"'"!"''.,._,, ~

~ 2.3. n <!n ,~l'ir

:.,,.,_"...,.,,,, ,,,,,,..,., _,,,,,,"''''''''..,,...., , - , ,..,.,,,,,,,,",,,... , ,~,",,,"{,,,,.,,,,,j,).,dooo..o"...Oo",o,;,,,,., , ,,,,w,., ..,.,,,,.,,,..,,...,ioo"ooiAO..ooooOoooOO" , .o,",.",~.,\. , ,.,"., , oo.,,,,,,.,, .... ,, ,,,,, ,, , , ,~,,ll< ... "~"<<lo"'"'"";

> import builtins


>>> dir(builtins)
n: ,

yl, strName, str_name.

n :

ly,

. . .

, . . .
~ , :

>
>>>
10

= 10

11

!( !

!!

: -
:

>
>

= 10;

(10, 20)

= 20

38

2.2.

Python 3

Python 3

/.

n :

bool- n . True False,


1 :

>>> type(True), type(False)


(<class 'bool'>, <class 'bool'>)
>>> int(True), int(False)
(1, 0)

NoneType- None ( ):
> type (None)
<class 'NoneType'>

None n False:

> bool(None)
False

int-

. n n:

>>> type(2147483647), type(999999999999999999999999)


(<class 'int'>, <class 'int'>)

float-

>>> type(5.1), type(8.5e-3)


(<class 'float'>, <class 'float'>)

cornplex-

n :

> type (2+2j)


<class 'cornplex'>

s t r - Unicode-cpo:
>>> type ("")
<class 'str'>

n :

bytes -

>>> type(bytes("Cpoa", "utf-8"))


<class 'bytes'>

bytearray-

n :

>>> type (bytearray ("", "utf-8"))


<class 'bytearray'>

list-

n.

> type ( [1, 2, 3]


<c1ass '1ist'>

tuple-

> type ( (1, 2, 3)


<class 'tuple'>

list

n-

39

2.

+ dict- . dict
:

>>> type( {"": 5,


<c1ass 'dict'>

"":

20} )

+ set- ( ):
>>> type ( {"",
<c1ass 'set'>

"",

""}

+ frozenset- :
>>> type (frozenset (["",
<c1ass 'frozenset'>

"",

""]))

+ ellipsis- Ellipsis. ellipsis


:

> type ( ... ) , ... , . . . is Ellipsis


(<c1ass 'e11ipsis'>, E11ipsis, True)
> c1ass ():
def _getitem_(se1f, obj): return obj
>

()

... , 1:5, 0:9:1, 0]


(E11ipsis, s1ice(1, 5, None), s1ice(O, 9, 1), 0)

>[

'

+.function--;- :
>>> def func(): pass
> type (func)
<c1ass 'function'>

+ modu1e :-:
> import sys
> type (sys)
<c1ass 'modu1e'>

+ type-

. !

Python

, !

>>> c1ass

pass

> type ()
<c1ass 'type'>
> type (type ( ""))
<c1ass 'type'>
.
,

>>> arr = [1, 2, 3]


> arr [0] =
>>> arr
[,

2, 3]

bytearray.
#

n n

40

, , n

bytes. ,

/.

Python 3

, ,
n:

>>> str1
>>> str2
>>> str

>

""

""

str1 + str2

print(str)

, .

, , , n bytes bytearray,
-.

_next_ () next ().

, :

>>> arr = [1, 2]


>>> i = iter(arr)
> i. next ()
1
> next (i)

next

()

next ( )

2
, :

>>> d = {"": 1,
>>> i = iter(d)
>>> i. next ()

":

2}

''

>>> d[i.
1

next

()]

. .

for,

II . n, n
:

>>> for i in [1, 2]:


print(i)
.
:

>>> for i in "":


print (i + " -", end=" ")
:
------

>>> d = ("": 1, "": 2}


>>> for key in d:
print( d[key]

2.

41

n , n
, (n

in).

2.3.

+), n (n *) n (n

n n .

Python n . , n n

n n n n

. n n n n= :

> = 7
>>> = 7.8
> s1 = ""
>>> s2 = ''
>>> = True

# int
# float
# s1
# s2
# True

n n:

> =
>>> ,
(10, 10)

10

n n , .
n nn n. nn n

n , ,
. :

>>>
>>>

=
,

[1, 2]

( [1, 2]'

[1, 2])

n n n n ~

. n nn :

>>> [1] = 100


>>> ,
([1, 100], [1, 100])

n, n
n . , n
, . n , n
11.:

> = [1, 2]
> = [1, 2]
> [1] = 100
>>> ,
([1, 2], [1, 100])

, n ,
n . ,

True:
>>>
>

is

[1, 2]

is

is.

42
True
> = [1, 2]
> = [1, 2]
>>> is
Fa1se

#
#

/.

Python 3

. , '

2, . :
>>> = 2; = 2; z = 2
>>> is , is z
(True, True)

>>> import sys


>>> sys.getrefcount(2)
304

getrefcount () sys:

sys

,
. , .

Python

=,

. ;

>>>
>>>

z
z

= 1, 2, 3

(1, 2, 3)
n .
;

>>> ,
(1, 2)
>>> ,

1, 2;

(2, 1)

. ,

, , ,

>>> ,; z = "123"
>>> , , z
( '1', '2', '3')
>>> , , z = [1, 2, 3]
>>> , , z
(1, 2, 3)
>>> , , z = (1, 2, 3)
>>> , , z
(1, 2, 3)
>>> [, , z]
(1, 2, 3)
>>> , , z

bytes

bytearray.

(1, 2, 3)
, =
, :

43

2.

>>> , , z = (1, 2, 3, 4)
Traceback (most recent 11 1ast):
File "<pyshell#130>", 1ine 1, in <modu1e>
, , z = (1, 2, 3, 4)
Va1ueError: too many va1ues to unpack (expected 3)

Python 3

n n,

(*). :

> , , *z =
> , , z
(1, 2, [3, 4])
> , *, z =
> , , z
(1, [2, 3], 4)
> *, , z =
> , , z
( [1, 2], 3, 4)
> , , *z
> , , z
(1, 2, [3])
> , , *z
> , , z
(1, 2, [])

(1, 2, 3,

4)

(1, 2, 3, 4)

(1, 2, 3, 4)

(1, 2, 3)

(1, 2)

, , ,
. , .

, .

>>> *, , *z = (1, 2, 3, 4)
SyntaxError: two starred expressions in assignment

2.4.

Python ,
. :

>>>
>

""

#
#

str

int

. , , type 1<
n>) :
> type ()
<c1ass 'int'>
:

>>> = 10
>>> if type(x) == int:
print (" int")

type 11,

44
t

1. Python 3

isinstance () :

>>> s = ""
>>> if isinstance(s, str):
print (" n str")

2.5.

Python

m ,
. ,
, . ,

Python-

, .

,
. , , . .
:

>>> 2 + "25"
Traceback (most recent 11 1ast) :
File "<pyshell#O>", line 1, in <modu1e>
2 + "25"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
:

( [ <> J ) -

. :

>>> 1(0), 1(1), 1(""),


(Fa1se, True, Fa1se, True)

1("")

int ( [<> [, < >] ] ) -

( -

>>> int(7.5), int("71")


(7, 71)
>>> int("71", 10), int("71", 8), int("Oo71",
(71, 57, 57, 10)

~),

10).

int("A", 16)

, :

>>> int ("71s")


Traceback (most recent 11 1ast):
File "<pyshell#9>", line 1, in <modu1e>
int ("71s")
Va1ueError: inva1id 1itera1 for int() with base 10: '71s'

float ( [< > J ) -

. :

>>> f1oat(7), f1oat("7.1")


(7 ., 7 .1)

>>> f1oat("Infinity"), f1oat("-inf")


(inf, -inf)
> float ("Infinity") + float ("-inf")
nan

2.

+ str ( [<> J ) -

45
. :

> str(125), str( [1, 2, 3])


('125', '[1, 2, 3]')
>>> str((1, 2, 3)), str({"x": 5, "": 10})
('(1, 2, 3)', "{'': 10, '': 5}")
>>> str( ts("", "utf-8") )
"b'\\xd1\\x81\\xd1\\x82\\xd1\\x80\\xd0\\xbe\\xd0\\xba\\xd0
\\'"

>>> str ( bytearray ( "", "utf-8") )


"bytearray(b'\\xd1\\x81\\xd1\\x82\\xd1\\x80\\xd0\\xbe\\xd0
\\xba\\xdO\\xbO')"

st r (<> [, <> [, < !1>] J ) - bytes


bytearray . "strict" (
UnicodeDecodeError; ),
"replace" ( , \uFFFD) "ignore"
( ). :

>>> obj 1 = bytes ( "1", "utf-8")


>>> obj2 = bytearray("cpoa2", "utf-8")
>>> str (obj1, "utf-8"), str (obj2, "utf-8")
('1',

'2')

>>> str(obj1, "ascii", "strict")


Traceback (most recent 11 1ast):
Fi1e "<pyshe11#16>", 1ine 1, in <modu1e>
str(obj1, "ascii", "strict")
UnicodeDecodeError: 'ascii' codec can't decode byte
Oxd1 in position 0: ordina1 not in range(128)
>>> str(obj1, "ascii", "ignore")
'1'

bytes (<>,

<> [,

< !1>] ) -

bytes. !l
),

"replace"

"ignore".

"strict"

>>> ts(";", "1251")


b'\xf1\xf2\xf0\xee\xea\xe0'
>>> ts("123", "ascii", "ignore")
' 123'

bytes (<>) - .
255 bytes. ,
Va1ueError. :

>>>
>>>

bytes([225, 226, 224, 174, 170, 160])

'\1\2\0\\\0'

>>> str (,

"866")

''

bytearray (<>, <> [, < !1>]) -

bytearray.

),

"replace"

"ignore".

"strict"

46

1.

Python 3

>>> bytearray("cpoa" 1 "1251")


bytearray(b'\xf1\xf2\xf0\xee\xea\xe0')

trr(<> J - n

255

>>>

bytearray.
Va1ueError. :

nn ,

= bytearray([2251 2261 2241 1741 1701 160])

>

bytearray (b '\xe1\xe2\xe0\xae\xaa\xa0' )
>>> str (bl "866" )
''

list (<'>J -

n.

>>> list("12345" )
[ 1111 2', '3' 1 '4. 1 '5' J
>>> list((11 21 31 41 5) J
[1 1 21 31 41 5]

11

tuple (<>) -

n n :

> tuple("123456" )
11
('1'1 '2'1 '3'1 '4'1 '5', '6')
> tup1e([11 . 2 1 3, 41 5])
#
(11 2, 31 4, 5)

n ,
. ,
n n (

input ( J.

2.4).

.. "\"'~,-~'<'"...1'~' ~~" t...- '#''"'''~ ~;~.. ~.. .,.......,..................,.,.. ,.... .,. ...... ,,_. .. '" ... ,. ~"

:~

~ 2.4. 'n.

-" - ""

..........................................................................,.............. ................. ............ ............................................................. ....................................................................................................:t

11 -*- coding: utf-8

input("x = " )
input (" = ")
= x.rstrip("\r"J

. rstrip ( "\r")
print ( + )
input ()

-*-

5
12

11

.n

11

11
11

3.2.0
3.2.0

(.

( .

1.7)
1.7)

n n , "512". ,
n , input ( J . i.t n
, n ( 2.5).
..............~,........ . ............ .............. ...... ..........., . ..... . .................... ~...... ~................................~..................................." ..'"""""'"'"'' "<"""''""''"""'" ''"'' ''' ''" ' "'"'"""' ' ~'"~""'''''''".1:

t' "''\'''"''" " ~ ~

~ 2.5. ~>,

: .....~ -- - - - ..... ............. ...~..... ....... .... ,. _ , , .._,.,.,., ,, .,_, , .,., .,.-,.,, ,~..........-........~......................-.),,," .... ,.,.,.. ,......,...-.~.....,_,_..,..,.. "''''-'""""''"''..............................,..,.. ,_",.,.,..,.,,,,,;

# -*- coding: utf-8 -*

= int(input("x = "))

int(input("y
print ( + )
input ()
=

"JJ

11

5
12

2.

47

17, .

, .
, .

2.6.

del

<1>[,

... ,

<N>]

>>> = 10;
10
>>> del ;
Traceback (most recent call last):
File "<pyshell#l>", line 1, in <module>
del ;
NameError: name '' is not defined
:

>>> , = 10, 20
> del ,

del:

n n n . n, n
n ,

n n , n n
. n, n

Python 3,

n.

3.1.

n n n:

+-

>>> 10 + 5
15
>>> 12.4 + 5.2
17.6
>>> 10 + 12.4
22.4

--:

>>> 10 - 5
5
>>> 12.4- 5.2
7.2
>>> 12 - 5.2
6.8

* -:
>>> 10 * 5
50
>>> 12.4 * 5.2
64.48
>>> 10 * 5.2
52.0

1 - . , n
. ,

3.

49

Pytho

2. Pytho 2
3 . :

, Pytho

>>> 10 1 5

2.0
>>> 10 1 3
3.3333333333333335
>>> 10.0 1 5.0
2.0
>>> 10.0 1 3.0
3.3333333333333335
>>> 10 1 5.0
2.0
>>> 10.0 1 5
2.0

+ 11- .
. :

>>> 10 // 5

2
>>> 10 11 3

3
> 10.0 11 5.0

2.0
> 10.0 11 3.0

3.0
>>> 10 11 5.0

2.0
>>> 10 11 3.0

3.0
>>> 10.0 11 5

2.0
>>> 10.0 11 3

3.0

%- :

>>> 10 % 5

>>> 10 % 3

1
>>> 10.0 % 5.0

0.0
>>> 10.0 % 3.0

1.0
>>> 10 % 5.0

0.0
>>> 10 % 3.0

1.0
>>> 10.0 % 5

0.0
>>> 10.0 % 3

1.0

/. ,th

50

**- n:

>>> 10 ** 2, 10.0 ** 2

(100, 100".0)

- () + (n):

>>> +10, +10.0, -10, -10.0, -(-10), -(-10.0)

(10, 10.0, -10, -10.0, 10, 10.0)


n, n n ,
n n, n. n

n, n- n .
, n ,
n , n n
. n .
n n
. n, n n
:

>>> 0.3 - 0.1 - 0.1 - 0.1


-2.7755575615628914-17

. , , n , n

. n n ,
n

decima1:

>>> from decima1 import Decima1


>>> Decima1("0.3'')- Decima1("0.1")- Decima1("0.1")- Decima1("0.1")

Decima1 ( '0.0')

3.2.

n n n . Pytln

n n n:

-- . nn:

>>>

100

>>>

# 01100100
# 10011011

& - :

>>>

>>>

>>> z =
>>>

100
75

"{:)

&

&

(1:)

'1100100 & 1001011

1 -

100
75
>>> z

1
> "{:) 1 {1:)
'1100100 1 1001011
>>>

>>>

# 01100100
# 01001011
# 01000000
{2:b)".format(x, , z)
1000000'

# 01100100
# 01001011
# 01101111
{2 :)". format (, , z)
1101111'

3.

51

+ - :
> = 100
# 01100100
> = 250
# 11111010
> 2 =
# 10011110
{1:}
{2:b}".fonnat(x, , z)
> "{:}
'1100100 11111010 = 10011110'

+ -

- n

n :

>
>
> z
> k

100
<< 1
<< 1
z << 2

#
#
#
#

=
=

01100100
11001000
10010000
01000000

+ - n- n n
n , n:

> = 100
> = >> 1
>>> z = >> 1
> k = z >> 2

#
#
#
#

01100100
001,10010
00011001
00000110

, :

>>> = -127
> = >>
> z = >>
>>> k = z <<
> m = k >>

3.3.

#
#
#
#
#

1
2
1
1

10000001
11000000
11110000
11100000
11110000


n n n:

+-

> print ( "1" +

"2"}

12

>
[1,
>
(1,

[1, 2, 3] + [ 4, 5,
2, 3, 4, 5, ]
(1, 2, 3) + (4, 5,
2, 3, 4, 5, )

*-

n:

>>> "s" * 20
'ssssssssssssssssssss'
> [1, 2] * 3
[1, 2, 1, 2, 1, 2]
> (1, 2) * 3
(1, 2, 1, 2, 1, 2)

52

in-

Python 3

. ,

>>>

/.

in

""

True:

" n"

True
>>>

"2"

in

" n"

False
>>> 2 in [1, 2, 3]' 4 in [1, 2, 3]
(True, False)
>>> 2 in (1, 2, 3)' in (1, 2, 3)
(True, False)

3.4.

=-
>>>
5

5;

Python:

+=- :

>>>
>>>
15

= 5;

+= 10

+ 10

>>> s = ""; s +=
> print(s)

+= :

""

-=- ~:

>>>
>>>
5

= 10;

-= 5

- 5

*=- :

>>>
>>>
50

= 10;

*=

~ =

* 5

*=

>>> s = "*"; s *= 20
>>> s
'********************'

/=- :

>>> = 10; /= 3
>>>
3.3333333333333335

1 3

>>>

53

3.

= 10.0;

/= 3.0

1 3.0

>

3.3333333333333335

+ 1/=- :
>>>
>>>

= 10;

//= 3

10.0;

//=

~ =

// 3

3
>>>

3.0

// 3.0

>

3.0

+ %=- :
>>>
>>>

= 10;

%= 2

%2

10;

%= 3

%3

** 2

>>>
>
1

+ **=- :
>>>
>>>
100

3.5.

= 10;

**= 2

=5

+ 10 * 3 1 2

1.

10

3,

. .

n .

2.

2,

. .

(
), .

3.

5,

. .

4.

>>> = 5 + 10 * 3 1 2
>>>
20.0
:
=

(5 + 10) * 3 1 2

54

/.

Python 3

n n J :

\.

1.

2.

3.

1 n

3.

2.

4. n n .
>>>
>>>
22.5

(5 + 10) * 3 1 2

nI n J n:

\. -, +, -, ** -

I , I n, ,

n. J nI nJ n**,

n n, n- .. n, i

-10 ** -2
:

- (10 ** (-2))

2. *, %, /, 11-

(n), , , -

3.

+,-- (), J.

4. <<, >>- 'Ii

5.

& - .

- .

7. 1 -

8. =, +=, -=, *=, /=, 1/=, %=, **=-

n.

n n n
n , , n .

> True

True () False (),

1 :

1 + 2

> False + 2

+ 2

2
n:

>>> = True;
))) ,
(True, False)

False

n (rue) 1.
(False). n ~ bool 1).

True :

, :

>>> bool(l), bool(20), bool(-20)


(True, True, True)
>>> bool(l.O), bool(O.l), bool(-20.0)
(True, True, True)

n :

> bool("O"), bool([O, None]), bool((None,)), bool(("x": 5})


(True, True, True, True)
n

, :

>>> bool(O), bool(O.O)


(False, False)

n :

>>> bool(""), bool([]), bool(())


(False, False, False)

False:

56

/.

Python 3

None:

> boo1(None)
Fa1se

4.1.

. :

==-:

>>> 1 == 1, 1
(True, Fa1se)

!= -

>>> 1 != 5, 1 != 1
(True, Fa1se)
<-:

>>> 1 < 5, 1 <


(True, Fa1se)

>-:

>>> 1 > , 1 > 5


(True, Fa1se)

<=-

>=- :

>>> 1 <= 5, 1 <= , 1 <= 1


(True, Fa1se, True)

>>> 1 >= , 1 >= 5, 1 >= 1


(True, Fa1se, True)
in-

>>> "" in " 11 n" #


True
>>> 2 in [1, 2, 3]' 4 in [1, 2, 3] #
(True, Fa1se)
>>> 2 in (1, 2, 3)' 4 in (1, 2, 3) #
(True, Fa1se)

in :

>>> "" in {"": 1,


(True, Fa1se)

is -

"":

2}, "z" in

{"":

1,

"":

2}

, .

>>> = = [1, 2]
>>> is
True

is True:

4.

>
>

[1, 2];

is

57

[1, 2]

Fa1se
,
. ,

2,

:
= 2; z = 2
is , is z
(True, True)

>>>
>>>

= 2;

w not:

)))

>>>

==

1;

True

> not

==

, not

(Fa1se, Fa1se)
, w rue, . .

not, Fa1se. , . .

not , .
.

in, not

> 2 in [1, 2,

3], 2 not in [1, 2, 3]

(True, Fa1se)
is, not
:

>

>

= [1, 2]
is , is not
(True, Fa1se)

>

>>> 1 <

10

< 20, 11 <


(True, Fa1se)

< 20

>!'
:

and- and - ~ . Fa1se, ,


> 1 < 5 and 2 < 5

# True and True

==

True

True

> 1 < 5 and 2 > 5


Fa1se
> 1 > 5 and 2 < 5
Fa1se
> 10 and 20, and 20, 10 and
(20, , 0)

# True and Fa1se

Fa1se

# Fa1se and True

Fa1se

/.

58

Python 3

or- or - . n Fa1se, ,
n - :

>>> 1 < 5 or 2 < 5


#
True
>>> 1 < 5 or 2 > 5
#
True
>>> 1 > 5 or 2 < 5
#
True
>>> 1 > 5 or 2 > 5
#
Fa1se
>>> 10 or 20, or 20, 10 or
(10, 20, 10)
>>> or "" or None or [] or "s"
's'

True or True == True


True or Fa1se

True

Fa1se or True == True


Fa1se or Fa1se == Fa1se

rue ,
1

==

and

!=

True:

True, True:
1

==

or

==

n n n:

1. <, >, <=, >=, ==, ! =, <>, is, is not, in, not in.
2. not-

3. and-

4. o r -

4.2.

if... else

n if ... e1se n
n n , , n . n
:

if

<
<,

[e1if

>:

m,

>

< ~>:

<,

m,

>

m,

[e1se:
<,

,
n ( n). , n
n n. n
.

Python

, . . n . -

4.

59

n , ,

4.1 ).

# -*- coding: utf-8 -*

= int ( input ("

% 2 == 0:
print (, "else:
prin.t (, "input ()

") )

if

")

")

, !'
:

* -*

coding: utf-8 -*-

= int ( input ("


%

2 =
else: print
input ()
if

:
(,

print (, ""-

") )

")
")

. ,
, :

f -*- coding: utf-8 -*= int ( input (" : ") )


if % 2 = : print (, end=" "); print ( ". else: print (, end=" "); print ("-

")
")

input ()
, , , . .
n
. ,

. , ,
:

1 -*- coding: utf-8 -*

if

= int ( input ("

") )

%2 =

0:
print (, end=" ")
print ("- ")
else:
print (, end=" ")
print ( "- ")
input ()
if ... else .
(

4.2).

60

:-,,.........,,...............,................................,...,....... .,. ,.'(...........,.,... ......


~

. . . ._......... .

,...,~.-~!t.t~

~ nr 4.2. eCJ<(bKtfJC n

..

Python 3

. . .... . y_,,.,.....,.............,..........,...........,..........,....,..........

~ ~~-~tr~- ~_..

;-..............,~. .~............-..~w............~-...~,.._",,....-.............................,.........v.~...........,.4"""~.
# -*- coding: utf-8 -*-

1.

,.~

l ......."

il.l..................................~ .......................................................................;

1i .......... ~. ............................

print("""ao ?

1 - Windows 7
2 - Windows
3 - Windows Vista
4

-'""')

os = input ( "J-1 , : : ")


# 3.2.0 (. . 1.7)
os = os.rstrip("\r")
if os = "1":
print (" -Windows 7")
e1if os = "2":
print (" - Windows ")
elif os = "3":
print (" - Windows Vista")
elif os = "4":
print (" - ")
elif not os:
print (" " )
else:
print (" ")
input()

elif

. ,
:

elif not os:


:

elif os

= "":

False,

True

. n

not.

n . n

( 4.3).

# -*- coding: utf-8 -*print("""ao ?

1 - Windows 7
2 - Windows
3 - Windows Vista
4 - :""')
os = input (" ,
os = os.rstrip("\r")

: :

3.2.0

")
( .

1.7)

4.

61

if os != "":

if

os = "1":
print (" - Windows 7")
e1if os == "2":
print (" - Windows ")
e1if os == "3":
print("B - Windows Vista")
e1if os == "4":
print (" - ")
e1se:
print ("
else:
print (" ")
input ()

")

i f ... e1se :
<>

< >

if

<>

e1se

< >

> print ("Yes" if 10

% 2

e1se "No")

Yes

> s
> s

"Yes" if 10 % 2 ==

e1se "No"

"Yes" if 11 % 2

e1se "No"

'Yes'

> s
> s
'No'

4.3.

for

,
n n

100

1 100

. n

print (1)
print (2)
print (100)
n n :

for

in range(1, 101): print(x)

, n n .

Python

n :

for whi1e. for n n

n. :

for

< >
<

in

<>:

>

[e1se:
<,

break>

62

/.

Python 3

n :

<>-

, n, , .;

+ .<

> -

+
+

< > - , ;
n break,
else. .

n n

..

:- ~ ottt

.......................

tt. ~-~ ~ ,.

f............
4.4. 1<
- ... ...
.............- .............- ...z................. ...."............:............
~

.:.-

4.4.

..,.......,..,..., .......,............... .......................,.,,...... ...... ....................t;............................,.

~t ,

~J,,............... ..........-

~.,

,~

....................................... ~........

# . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . .. . . . . . . . . . . . .

for s in "str":
print (s, end=" " )
else:
print ( "\n n")
n:

s t r
l

n n' ~ ( 4.5).
.. ~~'-""""'"''~"''.._.,,,.,..,_,~ ........ov....~"!""_',~"'''V'W-."t,,.,...._.,,,.,,..,.,. ,.,,.,"'" '''''''"" ''"''' "'''""''...-,...... ...........
_
_.,, ........ ., ... ,....,,.. ,.,,,,1,...... ,..,,,.,, ...._...~.,,.,,.,..,, ..,, ...,.,,....,.,.....

~-

! 4.5, n n

:..................... ~-........ ~ ....- .-..,.~ ..........,, .,/~;.....~....,,,,.,,,\......t,.,,;,,,,.~.,,,,,,.,,,,;,.,.,,.,."...,,..,.,,,,,,_,,,,,..,;,,, .. ,.,),,,,.,,..,.,..,,,.,,.,-,,,,,,,.,,,.,,,,.., ................. ,...,",,,, .......-.......,,.,,,,;,,,;,,,,,.. ,,,,,

in [1, 2, 3]:
print(x)
for in (1, 2, 3):
print(y)

for

for n n ,
. n n. ii

n n keys , dict_keys,
. n n n. ii
, n n
, (
:!"'-'"""

4.6).

""~"'1'-"'-"''' ' ''""''-'""'""' '"' ~"~""'"' '" '"'''""'-'''"'"''1""WI'"'' ''''~".v~"''"'''>'~'"''~'"''''' '' '''' ''' "''''''"'""''"'' ' ~'J ' ''''-"'''""'''''.''" ''""''''''"'"'' ""''' '"' "'~'~'"""''"'" ''''"'''''""''''

j r., 4.6.

f, ,,,,.,;,...,.,..,,,,.,.,,,.. ,.,.,.,h .....,,.,.,,...,.,.,,,,,,,,..,,,.,,.,.,,.,..,.,.,,.,,,."._,",,,.,,.,.,.,...,,.,,.,,,..,.,,,.,.,.,..,,.,.,,,.,.,,,.,,,,,,.,,,..,;,.,,.., ,,., ,,,, ,., ,,. ,.,,. .,,,,. ,,,f.,"""'""'~'""'''" "'' '''""''"""'"""""" .. ""'''''"'..,.

>>> arr = ("": 1, "": 2, "z": 3}


> arr. keys ()
dict_keys(['y', '', 'z'])
>>> for key in arr.keys():
# n
print(key, arr[key])

z 3

keys( )

4.

>>> for key in arr:


print(key, arr[keyl)

63

z3
, n n,
, . .
n, n

sorted ():

>arr = {"": 1, "": 2, "z": 31


for key in sorted (arr) :
p rint(key, arr(keyl)

1
2

z3
n for n . 1
n (

........................................................................

4.7).

~"''"'"'''''"''''''''''''''''

~ 4.7. n n

..".

......... ..............................................................................................,

''''''"'""''''''

lo_,,_.,,...,,..,,,,,,...,,,o~n,.,,"_,,,,,,,",,.,,,,.,..".,.,,,,,.,.,.,,,,.,,,.,",.,, ..,,,..,,,.,,.,,.;.",,,,,,,,.,,,,.,,,,,,,..,.,;,,.,,,.,,,,,.,,_.,",,,,,_,,.,...,.,,,...,.,,,.,,,,,,,,,,..,,,,,,,,,,,.,,,.,,,,,,,,,.,,,,,,,,,.,,,.,.,,.,,.,.,,,,,,,,.,,,,,,,,w,,,,.,,,,,,:

> arr = [(!, . 2), (3 , 411


> for , in arr:
print ( , )

11

12

34

4.4. range()

enumerate()

arr = [1 , 2, 3 1
for i in arr:
i =i * 2
print(ar r)

2:

n:

[1, 2, 3)

, . i

n .
n . n , , ,

range ()

range ()

range ( [ <>, ] <> [,

<>

1)

. n <> ,

no

n . .

, . n

64

/.

Python 3

<> , 1. ,

. for
.

2 (

4.8).
!"t""".,..., , ......., ..., .._.,,._.,,'l!.,.,_,.,",

.,.,,.,.,..,, ,...... ";,'"-" ' ""''"'-''''~'..,'".."""""'1:(~'""""''"'""'.'".."'-'"~tt~"'"""'r''" ''".''..'"'!' ''<!""'-''('''..,.''''''"'''"'~"""'""'~"'""'"~~ ".'"''''"'.,'~''''~"'"!"\~'l;!

~ fiC1"1r1H 4.8. J>()Q~ ~ {)

f..,,.,,;,.,,,..,,,..,,.,,;..,,,,,.)y..,.,,,.,u,,.~,.,.,,,i,..,,,,,;..,;,,;,,_,.,,.,,,,,.,..,,,..,\\;;,o.,,.";,...,, ...,,,.,,,\~,....,,.;,,,"..,..,.,,.,~;.,,,.,.,,,,,.,,~,.,,.,,,..,,..,.,,.,,.,,,_,,..,,,.,."'!o.to\o'l'o"''''""""''' ..''''"f.''""'''"'"''..-..""I."''"'"'''"''''"''"J

arr ; [1, 2, 3]
for i in range(1en(arr)):
arr[i] *; 2
print (arr)
#

n:

(2, 4.,

1en (1
range (). range () n
1en (arr) - 1. i

. ,
.

2,

print ().

range (). 1

100:

for i in range(1, 101): print(i)


.,, .

for i in range(100,

100 1:

-1): print(i)

~ .

100:

for i i n range(2, 101, 2): print(i)

Python 2 range () . Python 3

. ,
. ,
,

range (), list () ( 4. 9).


0

:'"\"~''' '''''''''' "''"''''' ' '''''"'""' '' I''~" ' ''""'"'''''''"I''"''''''''" '"-''1!"'""'~'\"'~'\\ ~-..."A~~~r.,..,-,:;?f''''''""'P"''"~'~"'"'.(-~ 'v..",o_.,,,,...,,,.w~v~t""'''''''..,'''''"~'''''"""'""'''''""'' '''''"':1

r-4.9.

range

:,,,,..:..,.o#<.oto.,.,,,,,,,_..,,,,..,,:,,,-,.,.;,,,,,,_.,\,,,,,,,.,,,,,,\;,:,n,,,,,,._.,,w.;,.., ... , ,,,,,.;v..,,.,..,,.h,{o\oHofo_.A,o,;'o\;foo".;.'''"'"''"W. oot~o"'t.t<ooitlltoo:;'io""''"'~t'>o(o,.,ow)ol><o:O~"'''"'''""''.,_,._,.,,.,,,,.,.,,,..,,,.,.,.t._.., .. ,oo,;,,(j,{,oAo04

>>> obj ; range(1en([1, 2, 3]))


> obj
range(O, 3)
>>> obj[O ] , obj[l], obj (2]
(0, 1, 2 )
> obj [0:2]
range(O, 2)
>>> i ; iter(obj)
>>> next (i ), next (i ), next( i )
(0, 1, 2)
>>> list (obj)
[0, 1, 2]
>>> 1 in obj, 7 in obj
(True, False)

n n

4.

65

Python 3.2, range

+ index (<>)

n :

- , .

Va1ueError. :

>>> obj = range(1, 5)


>>> oj.index(1), obj.index(4)
(0, 3)

>>> obj.index(5)

Va1ueError: 5 is not in range

+ 1t (<>)

, . :

>>> obj.= range(1, 5)


>>> obj.count(1), obj.count(10)
(1, 0)

enwerate (<>.[, start=O J) for


.

start . 2
, (

arr = [1, 2, 3, 4, 5, ]
for i, e1em in ewerate(arr):
if e1em % 2 == 0:
arr[i] *= 2
print (arr)
#

n:

4.1 0).

[1, 4, 3, 8, 5, 12]

enwerate

() , .
next () . ,
Stopiteration:

> arr = [1, 2]


> obj = enwerate(arr, start=2)
> next(obj)
(2, 1)
> next (obj)
(3, 2)
> next (obj)
Traceback (most recet 11 1ast):
File "<pyshe11#10>", 1i 1, i <modu1e>
next(obj)
Stopiteratio

for .

3 . 1349

4.5.

1.

Python 3

while

while n
. while :

, n r

< >

while

<>:

< u>

<>

[else:
<,

n n n

break>

while:

1. - nn .
2. , , n ,
n .

3. - , n <>.
4.

2.

5. n n break, n

i = 1
while i < 101:
print (i)
i

+= 1

else. .

1 100, n while ( 4.1 1).

11
11
11
11

< >
<>
<>
<>

<> , . n
, <Cti>+<C>.

Keyboardinterrupt,

n n . ,

n , .

100

1 (4.12) .

i = 100

while i :
print(i)
i

-=

, .
-. 11

4.

67

. . ,

False,

True

wh ile n .
.

while
2 ( 4.13).

11

for.

__. .,, ... ,.,,,., .. ",_,.,.,,.".,,.,,.,,...,.,,.,.\,..."..._~,,,,., , ,,,,,,,,,,,.,,Voo".,"'"''''''~I''.., ....,., . ,.,,.,,,,,HV'""''' ''' ''.' '''~''''''''"'''''''''~'""{'""'''''"'''''''"'"''''"'""''''"""'''"''""''" ' """"' '""""'' '" '"~'"''' '' .,.

, . 4 ~ 13. .~n n .

. . .. . . . . .

. . . . .

..

. .

:................................................:. ............................,.,....... ,..................-.4,,,, ..,-r .,u...............,.u......................................................................................................................................

arr = [1, 2 , 3)
i , count = , len (arr)
whi.le i < count:
arr(i) '*= 2
i += 1
print (arr)

tl

l:

(2 , 4, 6)

4.6. continue.

continue .
. n

1 100,

10 t (4. 1 4).

:"""'''"'1'0"'~'t""l"'''''l""";o" "''""l'''''"'''~''''l"<~-lo.o~l>'"..''..~~~-""'""'l'l_.''fi"'',0"' ' ''""..0;t0''N'0"'' "\''''''...,"''''!'""''""'"''""..,"..'""'"'''"'''""'"''I""'"''""'"'"'"'""'''"""'''''''~

~ 4.14. n oontinue

t .........;.u......... ~.............o........................................................~.........l o,,.. ,"''"'''''''"""''"'~.t ... , .......1..; ..~........ ~..... ;,, ...... ;,,.., ............ ~~..~....................; .., ....................................................;

for i in range (1 , 101):


i f 4 < i < 11:
continue
pri nt(i)

t1

4.7. break.
break .

1 100 n ( 4.15).

,:!""~-"-''"'''-'""'''""''''''''""""''""'''"''''"'"''"""'"'"'"'''"''"''"' ''"~ .. ,,.,,,,,,;ti~"'::"'~'~...,.,_'V""""'' ' """\'I'~' ' ":'""'"'"'"_.,'"~""'"'''"''~'"""'V.~"""'-:'''"'"''''''"'' ' "'''"'""'''''''"""''.+'""'' ' ~

4.15. n"--~"''

~
,~...................................................................
.,...,..,-... ........................................................................................................................................
........
...................
................................. ............'
~

i =1
while True:
if i > 100: break
print(i )
i += l

rue.
n . b reak
,

100 .

68

1.

Python 3

break , , . .

, .

while n break n n n
n. n n
n (
:~ ' ''\\' !\"' ., ~ .

4. 16).

:;ro n..., tt'"\''' ' '' r .,...... ,., '"' " ... ' '\' .,.., . , ,,, . " ''' . .., ,., .,,,.,, ..,,.,. .... ''\

' "''' ...~ .,. ... ,., ..., .. ''" '' '' .,.,.. ''' '''""''1' ..1

: 4.1~. :. ttnr
;,,_,,.................-......................................................
.......- ................
......................................................- ....,; .............................................................._,........- ........... .......
~

~-+

# -*- coding : utf- 8 -*rint ( "

summa
while

'stop'

n ")

=
rue:

input ( "
x.rstri p ("\r" )
if == "stop":

= int ()

")
#

break
surrma +=

print ("
input ()

3.2.0

(.

:",

summa)

~ :
'

'stop'
10
: 20
: 30
: stop
: 60

, n , .

1.7)

Python 3 n n:

+ i n t - . n n;
+ float- ;
+ comp1ex- n .
n n , n
n, n. n n,

n- n . , n

, n
, n n .

n .

n n:

>>> = ;
>>> , , z
(0, 10, -80)

10; z

-80

, ,
. n .
( ) 1:

>>> 1111111,
(255, 45)

01101

(
) 7:

>>> 7, 12, 777, 007, 0012, 00777


(7, 10, 511, 7, 10, 511)
( )

9 F ( ):

>>> 9,0, 10, OxFFF, Oxfff


(9, 10, 16, 4095, 4095)
() n n

( ):

> 10., .14, 3.14,

1120,

(10.0, 0.14, 3.14,

1.1+21,

2.5-12
2.5-12)

/. Python 3

70


. ,
:

>>> 0.3 - 0.1 - 0.1 - 0.1


-2.7755575615628914-17

. , , , 1
. ,

decimal:

>>> from decima1 import Decimal


>>> Decimal("O.") - Decimal("0.1") - Decimal("0.1") - Decimal("0.1")
Decima1 ( '0.0')
, ,

fractions:

>>> from fractions import Fraction


>>> Fraction("O.") - Fraction("0.1") - Fraction("0.1") - Fraction("0.1")
Fraction(O, 1)
>>> float(Fraction(O, 1))
0.0
>>> Fraction(O.S), Fraction("2.3"), Fraction(, 6)
(Fraction(1, 2), Fraction(23, 10), Fraction(1, 2))
:
<

>+<

>J

> 2+5J, 8j
( ( 2+5j)' 8j)

decimal frp.ctions,

. .

5.1.

int ( [<> [, < >]]) -

( 10). :

>>>
(7,
>
(0,

int(7.5), int("71", 10), int("Oo71", 8), int("OxA", 16)


71, 57, 10)
int(), int("Ob11111111", 2)
255)

float ( [< >]) -

>>> float(7), f1oat("7.1"), f1oat("12.")


(7.0,. 7.1, 12.0)
>>> f1oat("inf"), f1oat("-Infinity"), f1oat("nan")
(inf, -inf, n)

5.

71

> float ()
0.0

+ in (<>)

. :

>>> bini255), bin(1), bin(-45)


('01111111',

oct (<>) -

'',

'-01101')

. :

>>> oct(7), oct(8), oct(64)


( '7', '10', '100')

+ hex (<>)

. :

>>> hex(10), hex(16), hex(255)


('',
'010',
'Oxff')

+ round (<> [,

< n >] ) - ,

. 5, ,
. 5.
. 5,
. :

>>>
(0,
>>>
(1,
>>>
(2'
>>>
(3,

round ( . 4 9 ) ,
, 1)
round ( 1 . 4 9) ,
2, 2)
round ( 2 . 4 9) ,
2, 3)
round (3 . 4 9) ,
4' 4)

round(0.50), round(0.51)
round(1.50), round ( 1. 51)
round (2. 50), round (2. 51)
round(3.50), round (3. 51)

.
, :

>>> round(1.524, 2), round(1.525, 2), round(1.5555, 3)


(1.52, 1.52, 1.556)

+ abs (<>)

- :

>>> abs(-10), abs(10), abs(-12.5)


(10, 10, 12.5)

+ pow (<> 1

<> [ 1 < >] ) -

>>> pow(10, 2) 1 10
(1001 100, 271 27)

<> <>:

** 2 1 pow(3 1 3) 1 3 ** 3

, :

> pow(10, 2 1 2),


(01 , 1, 1)

+ max (<

(10

** 2)

% 2, pow(3 1 3, 2) 1 (3

>) -

** 3)

%2

> max(1~ 2, 3)1 max(3, 2, 3 1 1), max(1 1 1.0) 1 max(1.0 1 1)


(31 31 11 1.0)

72

/.

Python 3

min (<n >) - :


>>> min(1, 2, 3), min(3, 2, 3, 1), min(1, 1.0), min(1.0, 1)
(1, 1, 1, 1.0)

sum (<> [,

<

>]

)-

(, , ) < >.

, .
, . :

> sum( (10, 20, 30, 40)), sum( [10, 20, 30, 40])
(100, 100)
> sum([10, 20, 30, 40],.2), sum([], 2)
( 102, 2)

divmod(x, ) - ( //, % ):

# 13

>>> divmod(13, 2)
(,

==

* 2 + 1

1)

>>> 13 // 2, 13% 2
(,

1)

# 13.5

>>> divmod(13.5, 2.0)


( .0, 1. 5)

* 2.0 + 1.5

> 13.5 // 2.0, 13.5% 2.0


(., 1.5)

5.2.

math.

math ,
. ,
:

import math

n n

cmath.

math :

pi -

n:

>>> import math


>>> math.pi
3.14159253589793

>>> math.e
2.718281828459045
:

sin (), cos (), tan () -

~ (, ,

). ;

asin (), acos (), atan () - (, ,


). ;

5.

75

>>> random.choice ( 1"s", "t" "r"])


'r'
>>> random.choice ( ("s", "t", "r" ))
't'
1

+ shuffle (<n> 1,

< .

11

11

1. > J J -

. .

, ,

random .

>>>
>>>
>>>
18,

arr = 11, 2, 3, 4, 5,
random.shuff1e(arr)
arr

7, 8, 9, 10]

6, 9, 5, 3, 7, 2, 4, 10, 1]

+ sm1 (<>,

< >)-

. ,
. n
, . :

>>> random.samp1e("string", 2)
1'i', ' r' J
>>> arr = 11, 2, 3, 4, 5, , 7, 8, 9, 10]
>>> random.samp1e (arr, 2)
[7 , 10]
>>> arr 11 n
11, 2, 3, 4, 5, , 7, 8, 9, 10]
>>> random.samp1e (( 1, 2, 3, 4, 5, 6, 7), 3)
(,

3, 5]

>>> random.samp1e(range(300), 5)
(12,

1 94, 272, 46, 71]

( 5.1).

arr ,
choice (). 8 .

~'""t'I"".. 'I''"''"''' '" ' ''''''''''''''''""'"'''"'''""''''''"'''''''"'''''"'"''''''.,.,.,.,,,., ,..,'!''''''''"' ''''''' 'J''tt,:~o~~~_.l'f"''' '' ''J ''''I''''~ ' "'' ' ''''''''''''''''''''''''''''''"'''''ff""''"'''"""'''''"''''''''''"'"'''''1

~ r 5.1.

Ji;.,..,,.,.,..,;,,,, ,\,,,~,.,.,,,;, , ,,,,,,,.,,,;,,,,.,,,,.,~...,,.,,,..,.,.,,\, .,lf\.,,,~,.,,,..,,.,,..-;,...'4Aoo'"l;~.~.II>Oi'o"oioo/(,..;,,.,,., ... _.,...,,,,~., ..,,...,,,,;,..,",;"""' '''' ; ,.,,",r,,,,.",,",.~,, .. o,.,.,~";..,,,,,,,.,,.;,,,;,,,..,",,,.,,.. .,\,...,.,,,.,,,,.,,,.:

1 -*- coding: utf-8 -*~rt random # random


def passw_generator (count_char=8):
arr = [ , 1 1 , 1 , d, 1 , 1 , f, , 9
h, , , i, 1 , j
1

1n 1,

''

, ,,, ' 1

1 ,

1' 1 1q' 1 'r ', 's 11 1t 1' 'u 1, lv', 'w' 1


' 1 , 1 D', 1 1 , , F', 1G ',, , 1 , I 1 , 1 J',

'' ~ 'N', , '',

'0 1 , 'R', 1 S',

x,y,z 1 ,' 1 ','2',

''1 ~U', 'V',

', ''

',

k1

1 ,, , m1

'z 11

Ll,

'W',

3','4','5','6','7','8','9'~'0'J

passw = (]
for i in range(count_char):
passw.append(random.choice(arr))
return "".join(passw)
!W.

print( passw_generator(10)
print( passw_generator() )
input ()

11

ngODHE8J8x
zxcpkF50

.
. ,
, , (
+), (*), (

in).

, . n .
. -

- , n

n . ,
, ( 6.1 ).

[~~~~:~:i.~i~:~~~~:~~~~::~~~~:~:~!;::~~:~:~~~::~~::~~i~ii.'"': : : : : : : : : : .:~: : : : : : : : : ~: :~: : : : : : : :: : : : :: : ~: : : ~: : .: : : : :: : .: : : : : .:J


.>>> s, = "Python"
> s[OJ

no

''

>>> s [0) = "J"


#
Traceback (most recent call last) :
File "<pyshell#2>", line 1, in <module>
#
s [] = "J"
TypeError : 'str' object does not support item assignment
.
Pytho :

> "stri ng\xOOstring" #


'string\xOOstring'

Python 3 :

str - Unicode-cpoa. ,
(UTF~8. UTF-16 UTF-32) . ,
, Unicode
n . Unicode-cpoy
- :

>>> type ("")


<class 'str'>

77

>>> "cpoa".encode(encoding="cp1251")
b'\xf1\xf2\xf0\xee\xea\xe0'
>>> "cpoa".encode(encoding="utf-8")
b'\xd1\x81\xd1\x82\xd1\x80\xd0\xbe\xdO\xba\xdO\xO'

+ bytes-

255, .

bytes

, ,

.
, . :

>>> s = bytes("cp str", "1251")


> s[O], s[5], s[:], s[4:7]
(241, 116, b'\~f1\xf2\xf0', b'str')
>>> s
b'\xf1\xf2\xf0 str'

bytes , .

, ,

1en (1 ,

>>> 1en ("")


6

>>> 1en(bytes ("",

"1251"))

>>>
12

len(bytes("cpoa",

+ bytearraybytes,

"utf-8"))

bytearray

n ,

. :

>>> s = bytearray("str", "cpl251")


>>> s[O] = 49; s
#
bytearray(b'ltr')
>>> s.append(55); s
#
bytearray(b'ltr7')

, ,

"".

str.
bytes bytearray

, , ,
.

bytes

bytearray

6.1.

.+ str ( [<> [,

<> [, < >]] ] ) .

,
. , .

78

/.

Python 3

> str(), str([1, 2]),


('',

'[1, 2]',

'(3, 4)',

str((,
"{'':

4)), str({"x": 1})


1}")

>>> str(b"\xf1\xf2\xf0\xee\xea\xe0")
"b'\\xf1\\xf2\\xf0\\xee\\xea\\xe0'"

bytes.

, .

bytes

bytearray,

>>> str(b"\xf1\xf2\xf0\xee\xea\xe0",

"1251")

''

"strict"

Un.icodeDecodeError; ),
,

"replace"

\uFFFD) "ignore" ( ~t

):

>>> obj1 = ts("1", "utf-8")


>>> obj2 = bytearray("cpoa2", "utf-'-8")
>>> str(obj1, "utf-8"), str(Qbj2, "utf-8")
('1',

'2')

>>> str(obj1, "ascii", "strict")


Traceback (most recent call last):
File "<pyshel1#16>", 1ine 1, in <modu1e>
str(obj1, "ascii", "strict")
UnicodeDecodeError: 'ascii' codec can't decode byte
Oxd1 in position 0: ordina1 not in range(128)
>>> str(obj1, "ascii", "ignore")
'1'

>>>

'',

('',

>>>

"",

'',

'"":

'"":

5',

5',

"'':

"'':

5"

5")

print('Cpoa1\nCpoa2')

1
2

>>>

print("Cpoa1\nCpoa2")

1
2

(, )
;
, .

Python

. .
, .

. ,

\n . t

, n :

>>>

print("Cpoa1\\nCpoa2")

1\n2

>>>

print('Cpoa1\\nCpoa2')

1\n2

79

, , , ,
:

>>> "\"\": 5", '\'\': 5'


( '"": 5', "' ': 5")
, ( )
. :

>>> "string
SyntaxError: EOL while scanning string literal
n ,

\,

> "stringl \
string2"
'stringlstring2'
> ("stringl"
"string2")
'stringlstring2'
>>> ("stringl" +
"string2")
'stringlstring2'

, \, ,
:

>>> print("string\")

SyntaxError: EOL while scanning string literal


>>> print("string\\")
string\

n .

.
. :

>>> print(''
''')

'l

2
l
2

>>>

print("""Cpoal

2"

"")

l
2

nn , .

_ doc_

, .

,
:

/.

Python 3

> def test():


"""

"""

pass
>>> print(test.

doc

n, (

n) n
n .

r,

. , \n .
, : \

>>>

n:

print("Cpoal\nCpoa2")

>>>

print(r"Cpoal\nCpoa2")

l\n2

>>> print

(r"""l \n2'""')

l\n2

, :

>>> print(r"C:\Python32\lib\site-packages")
C:\Python32\lib\site-packages
, :

> pr.int (":\ \Python32\ \lib\ \site-packages")


C:\Python32\lib\site-packages
,
. , . :

> print(r"C:\Python32\lib\site-packages\")
SyntaxError: EOL while scanning string literal
>>> print(r"C:\Python32\lib\site-packages\\")
C:\Python32\lib\site-pacages\\

, ,
:

>>> print(r"C:\Python32\lib\site-packages" + "\\")


C:\Python32\lib\site-packages\
> print("C:\\Python32\\lib\\site-packages\\")
C:\Python32\lib\site-packages\
> print(r"C:\Python32\lib\site-packages\\"[:-l])
C:\Python32\lib\site-packages\

81

6.2.

- ,
, .

, ,

\n-

\r-

r:

\ t - ;

\ v-

\- ;

\- ;

\ f - ;

\- ( );

\"-;

\' -

\N- N. , \74

\xN- N. , \ j;

\\- ;

\uxxxx- 16- Uicode. , \u043a ;

\Uxxxxxxxx- 32- Uicode.

<;

,
, :

> print

("

\ n")

\ n

, :

> print

(" \\ ")

6.3.

, . ,
, , ,

. .
.

. :

>>> s = "Python"
> s[O), s[l], s[2],
('',
'', 't',
'h',

s[],
'',

s[4],

s[5]

'n')

, , ,

IndexError:

82

/.

Python 3

>>> s = "Python"
> s[10]
Traceback (most recent 11 last) :
Fi1e "<pyshell#90>", line 1, in <module>
s[10]
IndexError: string index out of range
.
, , , n

>>> s = "Python"
>>> sl-1], ~[len(s)-1]
( 'n',

'n')

,
:

>>> s = "Python"
#
>>> s[O) = "J"
Traceback (most recent 11 1ast) :
Fi1e "<pyshell#94>", 1ine 1, in <module>
. s [0] = "J"
#
TypeError: 'str' object does not support item assignment

, . ,

. :
[<>:<>:<>]

. <> , .
. <> ,

. , , ,

. <> , . 1.
.

. :

>>> s = "Python"
>>> s[:] #
'Python'

>>> s[::-1]
'nohtyP'

# , <>

>>> "J" + s[1:]


'Jython'

>>> s[:-1] #
'Pytho'

1en(s)-1

>>> s[0:1]
''

83

.
n n n :

>>> s[-1:]
'n'

1en(s)-1

, ,

> s[2:5] #

2, 3 4:

2, 3

'tho'
n

len ():

>>> len("Python"), len("\r\n\t"), 1en(r"\r\n\t")


(6, 3, 6)
n, 1 ,

for:

> s = "Python"
> for i in range(len(s)): print(s[i], end=" ")
:

Python
, 1 n
:

>>> s = "Python"

> for i in s: print (i, end=" ")


:

Python
n n+:

> print ( "1" +

"2")

12

, n '[ .

> print ("1"

"2")

12

, , 1
, :

>>> s = "1",
>>> type(s)
<c1ass 'tuple'>

"2"

, , . ,
, :

>>> s =

"1"

> print (s +

"2")

12

> print (s "2")


SyntaxError: invalid syntax

84

/.

Python 3

n (n, )
n n n n str ():

>>> "string" + str(10)

'string10'
n, n n n n

. n n*,

n n n n in:

>>> "-" * 20

'--------------------'
>>> "yt" in "Python"

True
>>> ''yt'' in ''Perl''

Fa1se

6.4.

n n + n .

n n n n
.

Pytho % .

forrnat () ,

:
<

% <>

n >

n <

> n,

%[

(<>)

[<>] [<>]

[ . <>]

<n n>

n n
<>. n n, n <>
, n n

n , . :

>>> "%s" % 10
'10'
>>> "%s - %s - %s" % (10, 20, 30)
'10 - 20 - 30'

n :

<>- . , n <>
, . :

>>> "% (name) s -

'Nik- 1978'

%(year) s" % { "year": 1978, "name": "Nik")

85

+ <>- . :

#-

(
) ( ),

, <>:

>>> print("%#o
77

12

%# %# ..

(77,

10, 10. 5))

12

> print("%#x %# %#" % (Oxff, 10, 10.5))


Oxff
> print("%#X %# %#" % (Oxff, 10, 10.5))
OXFF
>>> print("%#.0F %.0F" % (300, 300))
300. 300

- :

>>> '" %d' - '%05d "'


"'3' - '00003'"

--

(3, 3) # 5 -

. ,
. :

>>> "'%5d' - '%-5d'" % (3, 3) # 53' -

11

'3

>>> "'%05d' - '%-05d'" % (3, 3)


"'00003' - '3

n- .

. :

>>> " ' % d' - ' % d "' % (- 3, 3)


"'-3' -

3'"

+- , ,
. + n, n
. :

>>> "'%+d' - '%+d'" % (-3, 3)


"'-3' -

'+3'"

+ <>-

, :

>>> "'%10d' - '%-10d'" % (3, 3)


3' -

'3

>>> "' %3s' '%10s'" % ("string", "string")


"' string''
string'"
"*"
:

>>> "'%*s"%10s"' % (10, "string", "str")


str'"
string''

86

/.

Python 3

<>- .
. :

>>> import math


> "%s %f %.2f" % (math.pi, math.pi, math.pi)
'3.141592653589793 3.141593 3.14'

"*"

>>> "'%*."f"'% (8, 5, math.pi)


"' 3.14159"'

< >- . .

< > :

s - str ():
>>> print ("%s" %

(" "))

> print ("%s %s %s" % (10,


10 10.52 [1, 2, 3]

[1, 2, 3]))

r - repr ():
>>> print ( "%r" %
'

10.5~,

("

"))

'

ascii ():

>>> print("%a"% (""))


'\u0441\u0442\u0440\u043e\u043a\u0430'

- .
:

>>> for i in range(33, 127): print("%s

=>%"%

(i, i))

d i - :

>>> print("%d %d %d"% (10, 25.6, -80))


10 25 -80
>>> print("%i %i %i"% (10, 25.6, -80))
10 25 -80

- :

>>> print("%o % %"% (077, 10, 10.5))


77 12 12
>>> print("%#o %# %#"% (77, 10, 10.5))
77

12

12

- :

>>> print("%x % %"% (Oxff, 10, 10.5))


ff
>>> print("%#x %# %#"% (Oxff, 10, 10:5))
Oxff

87

+ , - :
> print("%X % %" % (Oxff, 10, 10.5))
FF
> print("%1!X %# %" % (Oxff, 10 , 10.5))
OXFF
f

F -

n:

> print("%f %f %f" % (300, 18.65781452, - 12.5))


300 . 000000 18 .657815 - 12 . 500000
>>> print("%F %F %F" % (300, 18.65781452, -12 . 5))
300.000000 18 . 657815 -12.500000
> print("%# . 0F %. 0F"% (300, 300))
300. 300

+ - n ( "" ):
> print ( " %

% "

% (3000, 18657 .81452))

3.000000+3 1.865781+4

+ - n ( "" ):
> print("%E
3.000000+03

%"

% (3000, 18657.81452))

1.865781+04

+ g - f

( n ):

> print("%g %g %g"% (0.086578, 0.000086578,


0.086578 8.6578-05 1.865-05

+ G-

1.865-005) )

f ( n 11):

> print (" %G %G %G" % (0 . 086578, 0.000086578,


0 . 086578 8.6578-05 1.865-05

1.865- 005 ) )

n n,
. & :

> print ("% %s" % ("- u" ) ) # u


Traceback (most recent call last) :
File "<pyshell#'SS>", line 1, i n <rnoclule>
print ("% %s" % ("- u")) u
T.y peError: not all arguments converted during string formatt il1g
> print ("%% %s" ., ("- " )) 11
%-

n n n L
. n '!r~ n %,
- . n (11r

6.2).

~~~~:~~3.~~~:~-~~~~~~~~~F.~~~~~~~::~:~~:~i.~F.f.~~i.~:~~::~~~::: ::~:~: : :~ ~: :~: : :~: : :~: : : : : : : ~: :~: : : : : : : : : :~: : : : : ::;:~:J


~ -*- coding: , utf-8 -*html = "'"'<html>
<head><tit1e>%(tit1e)s</title>
</head>

88

/.

Python 3

<body>
<h1>%(h1)s</h1>
<div>%(content)s</div>
</body>
</htm1>"""
arr = { "tit1e":
" ",
"h1":
" : n ",
"content": " "}
print(htm1% arr) #
input ()
i:

<htm1>
<head><tit1e>o :</tit1>

</head>
<body>
<h1> : n </h1>

<div>o </div>

</body>
</html>
I:

expandtabs ( [< n> J ) -

J (i
) J . ,

s'. :
>>> s = "1\t12\t123\t"
>>> "' %s "' % s. expandtabs ( 4)
"'1
12 123 '"
i .
,
~

"1\t"
"12\t"- ,

"123\t"- .

i .


, i :

>>> s = "\t"
>>> "'%s'- '%s"'% (s.expandtabs(), s.expandtabs(4))
'-'
>>> s = "1234\t"
>>> "'%s'" % s.expandtabs(4)
"'1234
I,

, J
:

>>> s = "12345\t123456\t1234567\t1234567890\t"
>>> "'%s"' % s.expandtabs(4)
"'12345
123456 1234567 1234567890

89

12,

+ center (<> [,

<> J )

4,

8,

12

8,

. .

4;

, . ,

. :

>>> s = "str"
>>> s.center(15), s.center(11, "-")
('
', '----str----')
str

15

, - , - :

>>> s = "str"
>>> "'%15s' '%-15s' '%s"' %' (s, s, s.center(15))
str' 'str
str
,
:

>>> s = "string"
>>> s.center(6), s.center(5)
('string', 'string')

+ 1just(<>[,

<>])-

. ,

.
, . :

>>> s = "string"
> s.1just(15), s.ljust(15, "-")
('string
', 'string---------')
>>> s.ljust(), s.ljust(5)
( 'string', 'string')

+ rjust (<> [,

<> J)

. ,
.
, . :

>>> s = "string"
>>> s.rjust(15), s.rjust(15, "-")
('
string', '---------string')
>>> s.rjust(), s.rjust(5)
( 'string', 'string' )

zfill (<>) -

. .
,

. :

> "5". zfill (20), "123456". zfill (5)


( '00000000000000000005', '123456')

90

6.5.

format ().

/.

Python

format()

Python 2.6.

\I ,

<>= <

**kwargs)

n opaa>.format(*args,

< n >

{ }

, :
{[<>] [!<>] [:<>]}

, , .

>>> print (" { { } } { } - n

ValueError.

{}".

format

1 },

("n",)

<> ( )
. .
.

format ()

. :

{l}- {2}".format(10, 12.3, "string")


#
'10- 12.3- string'
>>> arr = [10, 12.3, "string"]
> "{0}- {1}- {2}".format(*arr)
#
'10- 12.3- string'
>>> "{rnodel}- {color}".format(color="red", model="BW") #
'W -. red'
>>> d = {"color": "red", "model": "W"}
>>> "{model}
{color}".format(**d)
#
'W- red'
>>> "{color}
{0}".format(2010, color="red")
#
'red- 2010'
>"{}-

format ()

>>> arr = [10, [12.3, "string"] ]


> "{0[0]}- {0[1][0]}- {0[1][1]}".format(arr)
'10- 12.3- string'
> "{arr[O])- {arr[1] [l] }".format(arr=arr)
'10- string'
>>> c1ass Car: co1or, mode1 = "red", "W"
>>> car = Car ()
>>> "{O.model}
'W- red'

{O.color}".format(car)

, <> .

, :

91

> " { ) - { ) - { ) - { n J " fonat ( 1, 2, 3, n=4 ) # " { J

{ 1}

{2}

{n}"

'1-2-3-4'

> "{}- {}- {n}-

{}".fonat(1,

2, 3, n=4) # "{0)- {1)- {n)- {2}"

'1-2-4-3'
<> , n n
. "s", str (),

. "r", repr (), "", ascii (). n


, n n str ().
:

> print (" {0! s)". fonat (""))

# str ()

> print (" {! r)". format

# repr ()

(""))

''

>

# ascii()

print("{O!a)".format("cpoa"))

'\u0441\u0442\u0440\u043e\u043a\u0430'
<> , :

[ [<>] <>]
[.<>] [ <>]

[<>]

[ #]

[] [<>]

[, ]

<> n. n
, n:

> '"{0:10}'
3'

'{1:3}"'.fonat(3,

"strig"}

'strig'"

n n n fonat (.).

n :

>
'"

"'{0:{1))'".fonat(3,

10} # 10-

3'"

' n .

n n <>. :

t <-
t >-

n ;

+ '- n. :
> '"{0:<10}' '{1:>10)'

'{2:10)'".format(3,

31

'" 3

3, 3)

+ =- , n :
> '"{0:=10)'
3'

'{1:=10)'".fonat(-3,.
1

3)

3'"

n n, n
n, n . n

n , . n n:

> '"{0:=010}'
11

'-000000003 1

'{1:=010}'".fonat(-3,

0000000003'"

3)

92

/.

Python 3

, <>.

, :

>>> '"{0:0=10}' '{1:0=10}"'.format(-3, 3)


"' -000000003' '0000000003' "
>>> "'{0:*<10}' '{1:+>10}' '{2:.10}'".format(3, 3, 3)
"'3*********'

'+++++++++3' ' .... 3 ..... '"

<>. :

+- , \.
;

+
+

-- ( );
- ~ .

. :

>>> "'{0:+}' '{1:+}' '{0:-}' '{1:-}"'.format(3, -3)


"'+3'

'-3' '3'

'-3'"

>>> '"{0: }' '{1: }"'.fonnat(3, -3)


"1

3'

'-3'

11

<> :

- :

>>> "' {:}' '{:#} "' .format (3)


" ' 11 ' ' 1 "'

- :

>>> "'{0:c}'".format(100)
"'d'"

+
+

d -
n-

d,

. ,

>>> import 11
>>> 1oca1e.set1oca1e(1oca1e.LC NUERIC, 'Russian_Russia.1251')
'Russian Russia.1251'
> print("{O:n}".format(100000000) .rep1ace("\uffa0", ""))
100 000 000

Python 3.2.0

\uffaO,

. ,

rep1ace ().

2.6

\ .

Python 3.2.0

\, format () 11:

>>> import 11
>>> 1oca1e.setlocale(locale.LC_NUERIC, "Russian_Russia.1251")
'Russian Russia.1251'
>>> print(locale.format("%d", 100000000, grouping=True))
100 000 000
>>> locale.localeconv() ["thousands_sep"]
'\'

93

n, :

> print (" {:, d}".

fonat

( 100000000))

100,000,000

+ - :
> "'{O:d}'

'{:}'

"' 511'

'777'"

'777'

'{0:#o}'".format(511)

+ - :
>

"'{:}'

"'ff'

'{O:#x}"'.fonat(255)

'Oxff'"

+ - :
>

'

"'{:)'

FF'

'{O:#X}'".format(255)

' OXFF' "

n <>
:

+f

F - n:

> "'{O:f}' '{i:f}' '{2:f}"'.format(30, 18.6578145, -2.5)


'" 30.000000'

'18. 657815'

'-2. 500000 "'

n n n n <>:

> "'{0:.7f}' '{1:.2f}"'.format(18.6578145, -2.5}


"'18.6578145'

'-2.50'"

+ - n ( "" ):
>

"'{:}'

'{1:e}"'.format(3000, 18657.81452)

"' .+'

'1.865781+4'"

+ - n ( "" ):
>
"'

"'{:}'

'{1:E}"'.fonat(3000,

.+'

+ g - f
> "'{O:g}'
"'0.086578'

18657.81452)

'1.865781+04'"

( n ):

'{1:g}'".fonat(0.086578,

0.000086578)

'8.6578-05'"

+ n- g, ;
+ G - f ( ):
> "' {O:G}' '{1:G} "' .fonat (0.086578, 0.000086578)
"'0.086578'

'8.6578-05"'

+ %- 100 .
f. :

> "'{0:%}' '{1:.4%}"'.format(0.086578, 0.000086578)


"'8. 657800%'

'0.0087%'"

94

/.

Python 3

6.6.
:

str ( [<> J) -

". n ,

. print ()

> str(), str([1, 2]), str("(3, 4)), str({"x": 1})


('',

[1, 2]',

"{'':

'(3, 4)',

1}")

>>> print ( "1 \n2")


1
2

repr (<>) - . n

Python Shell

IDLE.

>>> rr(""), repr([1, 2, 3]), repr({"x": 5})


( " ' ' " , ' [ 1 , 2 , 3] 1 , " { ' 1 : 5 }" )
>>> repr ( "1 \n2")
"'1\\n2'"

ascii (<>) - n .

ASCII.

>>> ascii([1, 2, 3]), ascii({"x": 5})


('[1, 2, 3]',

>>>

"{'

5}")

ascii("cpoa")

"~\\u0441\\u0442\\u0440\\u043e\\u043a\\u0430'"

1en (<>) -

>>> 1en("Python"), 1en("\r\n\t"), 1Em(r"\r\n\t")


(6, 3, 6)
>>> 1en ("")

strip ( [<> J) -

. : , n

(\r),

(\t)

(\n),

(\v) :

>>> s1, s2 = "


str\n\r\v\t", "strstrstrokstrstrstr"
>>> "'%s'- '%s'"% (s1.strip(), s2.strip("tsr"))
"'str' - 'ok'"

1strip ( [<> J) - n :
>>> s1, s2 = "
", "strstrstrokstrstrstr"
str
>>> "'%s'- '%s'"% (s1.1strip(), s2.1strip("tsr"))
' - 'okstrstrstr'"
"' str

rstrip ( [<> J) - n. :
>>> s1, s2 = "
str
", "strstrstrokstrstrstr"
>>> "'%s'- '%s'"% (s1.rstrip(), s2.rstrip("tsr"))
str' - 'strstrstrok'"

95

+ split ( [<> [,

<> J J)

None, .

, .

, ,
. :

> 5 = "word1 word2 word3"


>>> 5.5p1it(), 5.5p1it(None, 1)
(['word1', 'word2', 'word3'], ['word1',
> s = "wordl \nword2\nword3"
>>> 5.5plit("\n")
[ 'wordl' '. 'word2', 'word']

'word2 word3'])

,
:

>>> 5 = "word1
> 5.5plit ()
[ 'word1 ', 'word2',

w6rd2

word

'word']

>>> s = ""wordl"word2"word3""
>>> s.5plit(",")
(' ', ' ' , 'wordl' / ' ' , 'word2' ,
>>> "1"2"3".5plit(",")
[ 1 1',
1 1'
121, 1 1 , 1 3']

'word',

'']

, ,
n :

> "word1 word2 word3".5plit("\n")


['word1 word2 word3']

+ r5lit([<>[,

<>]])- , 5plit(),

- , , , .
:

>>> 5 = "word1 word2 word"


>>> 5.r5plit(), 5.r5plit(None, 1)
(['word1', 'word2', 'word3'], ['word1 word2',
> "word1 \nword2\nword3" .r5plit ("\n")
['word1', 'word2', 'word3']

+ splitline5 ( [True])

'word3'])

- (\n)

. ,

rue. ,
. :

> "word1\nword2\nword3".5plitline5()
[ 'word1 ' , 'word2 ' , 'word ' ]
> "word1\nword2\nword3".5plitline5(True)
['word1\n', 'word2\n', 'word3']
> "word1\nword2\nword3".5plitline5(Fal5e)

96

/.

Python 3

[ 'wordl ' , 'word2 ' , 'word ' ]


>>> "wordl word2 word".splitlines()
['wordl word2 word']

parti tion (<>)

- n -

. ,
n n , - -,

- , n n -. n

n. - , n
, n. :

>>> "wordl word2 word".partition(" ")


('wordl', ' ', 'word2 word3')
>>> "wordl word2 word".partition("\n")
( 'wordl word2 word', '', '')

rparti tion (<>) -

parti tion (),

n n, , , n .
, n n,
. :

>>> "wordl word2 word".rpartition(" ")


('wordl word2', ' ', 'word')
>>> "wordl word2 word".rpartition("\n")
(' ', '', 'wordl word2 word3')

join () -

n n .

. :
<>

<>.jin(<>)

n n n :

">>> "=> ".join(["wordl", "word2", "word"])


'wordl => word2 => word'
>>>" ".join(("wordl", "word2", "word"))
'wordl word2 word'
, n ~ ,

TypeError:

>>>" ".join(("wordl", "word2", 5))


Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
"".join(("wordl", "word2", 5))
TypeError: sequence item 2: expected str instance, int found
, n . nn
, .
n n n
, n

join ()

>>> s = "Python"
>>> arr = list(s); arr
['',

'',

't',

'h',

>>> arr [] = "J"; arr

'',

list (), n

n n . :

'n']

97

['J', '', 't', 'h', '',


>>> s = "".Join(arr); s
'Jython'

no

Python 3

'n']

bytearray,

>>> s = "Python"
= bytearray(s, "1251");
bytearray(b'Python')
> [] = ord("J");
bytearray(b'Jython')
>>> s = b.decode("cpl251"); s
'Jython'

>

6.7.

( )

set1oca1e () 11. , n
n :

import

11

set1ocale () :

set1oca1e

(<>

[,

<>])

<> n :

+ locale .LC_ALL- ;
+ loca1e. LC _ COLLATE- ;
+ loca1e. LC _- n ;
+ 11. LC_ MONETARY- ;
+ 11. LC_ NUERIC- ;
+ loca1e.LC_TIME- .
n getloca1e ( [<> J).
n n

UTF-8,

Windows

Windows-1251,

loca1e. LC_ COLLATE (

6.3 ).

:'",............................ ,,._,,,,,,,,,_,,,..,,,._,,.,.,,,~ ..'''"'""'':'''"'''''"."'"'"'"''\'.'',:::'"''"""'.'~~.~""'''"'.''',:'.'''''"""''~.'.'''.'''"'"'"''''"""'"".'''''"'""'".''''""'"''''"'"'''"'''""'" '""'""'""'''"'''''''''

lJ1 6.3. 110

. .

;..;..":"'"""'""'"""''''""'""'""' ............ : ............ :............ ; ......................... :ii ..............:.................~.i~ ................................................................................ ' ............................................. .

> import 1ocale


> # windows-1251
> loca1e.setloca1e(1oca1e.LC_ALL, "Russian Russia.l251")
'Russian Russia .1251'

> #
> 1oca1e.set1oca1e(locale.LC_ALL, "")
'Russian Russia .1251'
>>> #
> 11. get locale ()
('Russn_Russia',
'1251')
4 . 1349

98

/.

Python 3

>>> # locale.LC COLLATE


>>> locale.getlocale(locale.LC_COLLATE)
( 'Russian_ Russia', '1251')

localeconv ().
Russian Russia .1251

.
:

>>> locale.localeconv()
{'mon_decirnal_point': ', ', 'int_frac_digits': 2, 'p_sep_by_space': ,
'frac_digits': 2, 'thousands_sep': '\', 'n_sign_posn': 1,
'decirnal_point': ', ', 'int_curr_symol': 'RUR', 'n_cs_precedes': ,
'p_sign_posn': 1, 'mon_thousands_sep': '\', 'negative_sign': '-',
'currency_symol':
'.',
'n_sep_by_space': , 'mon_grouping': [3, 0],
'p_cs_precedes': , 'positive_sign': '', 'grouping': [3, ]}

6.8.

upper () - :
>>> print

("".

upper ())

lower ( J - :
> print

(""

.lower () J

swapcase () - ,
-:

>>> print ("

swapcase () )

capi talize () - :
>>>

print.("cpoa "

".

.capitalize ())

ti tle ( J - :
>>> s = "
>>> print(s.title())

"

6.9.
:

chr (<

> J -

>>> print(chr(1055))

99

ord (<>) -

>>> print(ord(""))
1055

6.1 .

. ,

find () -

. ,
-1. . :
<>.find(<>[,

<>[,

<>]])

, .

<> <> ,

<>[<>:<>]

r. :

>>> s = " "


>>> s. find (""), s. find ("") , s. find ("")
(0, 14, -1)
>>> s.find("p", 9), s.find("p", , 6), s.find("p", 7, 12)
(-1,

7)

index () -

find (),
ValueError. :

<>.ind(<>[,

<>[,

<>]])

>>> s = " "


>>> s.index("p"), s.index("p", 7, 12),
(0, 7, 14)
>>> s.index("ec")
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
s. index ("")
Va1ueError: substring not found

rfind () -

s.index("p",

1)

. , ~ -1.
. :
<>.rfind(<>[,

<>[,

<>]])

, .

<>

<> ,

. :

>>> s = " "


>>> s.rfind("p"), s.rfind("p"), s.rfind("ec")

100
(7, 21, -1)
>>> s.find("p",
(0, 14)

rindex () -

6),

s.find("p",

/.

Python 3

10, 20)

rfind (),

n ,

Va1ueError. :
<>.rind(<>[,

<>[,

<>]])

>>> s = " "


>>> s.rindex("p"), s.rindex("p"), s.rindex("p",
(7, 21, 0)
>>> s. rindex ("")
Traceback (most r~cent cal1 1ast):
Fi1e "<pyshe11#30>", 1ine 1, in <modu1e>
s. rindex ("")
Va1ueError: substring not found

count () -

6)

. n

, . .
:

<>.unt(<>[, <>[, <>]])


:

>>>
>>>
(2,
>>>

s = " "
s. count ("") , s. count ("", 6) , s. count
1, 2)
s.count ("")

("")

startswith () -

n, n.

True, - False.

. :
<Cpoa>.startswith(<ocpoa>[,

<>[,

<>]])

n , .
I <> <> J, Jn ,

. :

>>> s = " ,"


>>> s.startswith("p"), s.startswith("p")
(True, Fa1se)
>>> s. startswith ("", ), s. startswith ("", 14)
(Fa1se, True)

2.5;

<> i :

>>> s = " "


>>> s. startswi th ( ("", "") )
True

endswith () -

, n.

,
.

True, n - Fa1se.

101

:
<>.nd5with(<>[,

<>[,

<>]])

, .
<> <> , ,
. :

>>> 5 = " "


>>> 5 .end5with (""), 5 .end5with ("")
(Fa15e, True)
>>> 5.end5with("oa", , 9)
True

2.5,

<> :

>>> 5 = " "


>>> 5.end5with( ("", ""))
True

rep1ace () -

.
. :
<>.r1(<

D,

< >[,

<

>])

>>> 5 = ", "


>>> print(5.rep1ace("e",
,

>>>

print(5.rep1ace("ne",

""))

""))

>>> 5 = "5tr5tr5tr5tr5tr"
>>> 5.rep1ace("5tr", ""), 5.rep1ace("5tr",
1 1
1
,
(
5tr5tr 1 )

3)

tran51ate (< >) - <


>. < > ,
Unicode-o , - Unicode-o
.

None, .

n "", "":

>>> 5 = ""
>>> d
{ord(""): None, ord("p"): ord("P")}
>>> d
{1088: 1056, 1055: None}
>>> 5.tran51ate(d)
1

<

>

5tr.maketran5(<X>[,

<>[,

<Z>]J)

maketran5 ().

102

/.

Python 3

, :
>>> t = str.maketrans({"a": "", "":
>>> t
{1072: '', 1089: None, 1086: ''}
>>> "cpoa".translate(t)

"",

"":

None})

''

, .
<> ,
, <>. :

>>> t = str .maketrans ( "", "")


>>> t
{1072: 1040, 1073: 1041, 1074: 1042, 1075: 1043, .1076: 1044,
1077: 1045, 1078: 1046, 1079: 1047, 1080: 1048}
>>> "aC>e".translate(t)
''

None. translate ()

. , :

>>> t = str .maketrans ( "123456789", "" * 9, "str")


>>> t
{116: None, 115: None, 114: None, 49: 48, 50: 48, 51: 48,
52: 48, 53: 48, 54: 48, 55: 48, 56: 48, 57: 48}
>>> "strl23456789str".translate(t)
'000000000'

6.11.

isdigit () - rue, ,
False:

> "0123".isdigit(), "123abc".isdigit(), "abcl23".isdigit()


(True, False, False)

isdecimal () -

True, ,
False. ,

ASCII,

. :

>>> "123".isdecimal(),
(True, False)

isnumeric () -

"123cp".isdecimal()

True, ,
False. ,

ASCII,

. :

>>> "\u2155".isnumeric(), "\u2155".isdigit()


(True, False)
>>> print("\u2155") # "1/5"

isalpha () -

103
rue, ,

- False. , False. :

>>> "string".isalpha(), "cpoa".isalpha(), "".isalpha()


(True, True, False)

>>> "123abc".isalpha(), "str str".isalpha(), "st,st".isalpha()


(False, False, False)

isspace () - rue, ,
- False:

>>> "".isspace(), "\n\r\t".isspace(), "str str".isspace()


(False, True, False)

isalnum () - True, () ,
' - False. , False. :

>>> "0123".isalnum(), "123abc".isalnum(),

"ac123".isalnum()

(True, True, True)

>>>

"cpoa".isalnum()

True

>>> '"' .isalnum(), "123

"

.isalnum(),

",

123.". isalnum()

(False, False, False)

islower () -

rue, , -

, - False. ,
. :

>>> "srting".islower(),

"cpoa".islower(), '"'.islower()
(True, True, False)
>>> "srtingl".islower(), "str, 123".islower(), "123".islower()
(True, True, False)
>>> "STRING". islower (), "". islower ()
(False, False)

isupper () -

True, ,

, - False. ,
. :

>>> "STRING". isupper (),

"". isupper () , "". isupper ()


(True, True, False)
>>> "STRINGl".isupper(), ", 123".isupper(), "123".isupper()
(True, True, False)
>>> "string". isupper (), "STRing". isupper ()
(False, False)

istitle () -

rue, ,

, - False.
, . :

>>> "Str Str".istitle(), " Cp":istitle()


(True, True)

>>> "Str Str 123".istitle(),


(True, True)
>>> "Str str".istitle(),
(False, False)

"

123".istitle()

" cp".istitle()

104

/.

Python 3

>>> "".istitle(), "123".istitle()


( False, False)
n (.

4.16)

, n, , n ~1
n ( 6.4). . n
.

~'"'"'''""'""''""'''"""''"'''"'''''~--"''""'"""'"''"''''''''''''''"''''"''''''"""''''''''''"'"'"''"''"''"'"''''"'''''''''''"'''''''''''"'''"'''''''''''''''"''''''"'''"'"'''''

l .4._.t.il.t()!;!~~Qn~kJ"1~&

# -*- coding: utf-8 -* 'stop' n ")


sWl1!11a =
while True:
= input: (" : ")
= x.rst:rip("\r")
# 3.2.0 (.
if == "stop":
break #
if == "":
print (" 1 ")
continue
if [] == "-": # n
if not x[l:] .isdigit(): #
rint("

rint("

'")

continue
else: # ,
if not x.isdigit(): #
print (" , !")
continue
;..; = int () #
SW11111a +=
print("Cya :", SW11111a)
input ()
n :

-5

-str

str

10

'

'stop'

'

'

stop

1.7)

, n, n .

....., ..........................

_.

.......

6.12.

105

str

bytes

n , ,

? , ,

. n Uriicode-cpoy. n

Python 3
bytearray, n n
n 255. . n
bytes n, , n bytearray---,-
n

bytes

, n.

bytes

n:

bytes ( [<>,

<>

[,

< >]]

).

, n . n
n

bytes,

n n n.

n n,

TypeError.

>>> bytes ()
''

>>> ts("", ""1251")


b'\xf1\xf2\xf0\xee\xea\xe0'
>>> bytes ("")
Traceback (rnost recent 11 1ast):
File "<pyshell#>", 1ine 1, in <rnodu1e>
bytes ("")
TypeError: string argurnent without an encoding
n

"strict"

(n

UnicodeEncodeError;aee

),

n)

( ).

no
"ignore"

"replace"

>>> bytes ("string\uFFFD", "1251 "., "strict")


Traceback (rnost recent 11 1ast):
Fi1e "<pyshe11#35>", 1ine 1, in <rnodu1e>
bytes ("string\uFFFD", "1251", "strict")
Fi1e "C:\Python32\1ib\encodings\cp1251.py", 1ine 12, in encode
return codecs.charrnap_encode(input,errors,encoding_tale)
UnicodeEncodeError: 'charrnap' codec can't encode character
'\ufffd' in position 6: character rnaps to <undefined>
>>> bytes("string\uFFFD", "1251", "rep1ace")
' string?'
>>> bytes("string\uFFFD", "1251", "ignore")
b'string'

encode([encoding="utf-8"] [, errors="strict"]).

, n n

UTF-8. n errors "strict" ( no


), "replace", "ignore", "xmlcharrefrep\ace" "backslashreplace". :
>>>

"".nd()

b'\xd1\x81\xd1\x82\xd1\x80\xd0\Xe\xd0\xba\xd0\x0'

>>> "cpoa".encode(encoding="cp1251")
b'\xf1\xf2\xf0\xee\xea\xe0'

106

>>>

/.

Python 3

"cpoa\uFFFD".encode(encoding="cp1251",

errors="xrn1chairefreplace")
b'\xf1\xf2\xf0\xee\xea\xe0&#65533;'
>>> "cpoa\uFFFD" .. encode (encoding="cp1251",
errors="backs1ashrep1ace")
b'\xfl\xf2\xf0\xee\xea\xe0\\ufffd'

( ) , ,
. ,
,

ASCI\.

>>> b"string", b'string', b"""string'"'", '' 'string'''


(b'string', b'string', b'string', b'string')
>>> ""
SyntaxError: bytes can on1y contain ASCII 1itera1 cha~acters.
>>> b"\xf1\xf2\xf0\xee\xea\xe0"
b'\xf1\xf2\xf0\xee\xea\xe0'

bytes (<>),
255 bytes.
Va1ueError. :

>>>
>>>

= bytes([225, 226, 224, 174, 170, 160])

'\1\2\0\\\0'

>>> str (,

"866")

''

bytes (<>),

. . :

> bytes (10)


'\00\00\00\00\00\00\00\00\00\00'

bytes. fromhex

(<>)

>>>
>>>

= bytes.fromhex("

20

")

'\1\2\0\\\0'

>>> str (,

"866")

''

bytes .
255, .
, ,
, , :

>>> = bytes("string",
>>>
b'string'
> []

"1251")

115

> [1:3]
b'tr'

>>> + "123"
b'string123'
> * 3
b'stringstringstring'
>>> 115 in , b"tr" in
(True, True, Fa1se)

107

b"as" in

, ,
. ,
. ,
:

>>> 1ist(bytes("string", "1251"))


[115, 116, 114, 105, 110, 103]

bytes

. ,

, :

>>> = bytes("string", "1251")


> [] = 168
Traceback (most recent 11 1ast):
Fi1e "<pyshel1#76>", line 1, in <modu1e>
[] = 168
TypeError: 'bytes' object does not support item assignment

bytes , -

, ,

3.2.0,

str, bytes. encode (),


isidentifier (), isprintale (), isnurneric (), isdecima1 (), forrnat_map () format (),

. ,

bytes, :

>>> = bytes("string", "1251")


>>> b.rep1ace(b"s", b"S")
b'String'
,

bytes

. ,
:

>>> b"string" + "string"


Traceback (most recent 11 1ast):
Fi1e "<pyshel1#79>", 1ine 1, in <modu1e>
b"string" + "string"
TypeError: can't concat bytes to str
>>> b"string" + "string".encode("ascii")
b'stringstring'

bytes , .

.
, ,

1en () , :

108
>>>
6
>>>
6
>>>
12

/.

Python 3

ln("")

len(bytes("cpoa",

"1251"))

len(bytes("cpoa",

"utf-8"))

bytes n decode ().

decode ( [encoding="utf-8"] [, errors="strict"])

encoding ( UTF-8) . bytes,


n errors- n n n. errors

"strict" ( ), "replace" "ignore".

>>> = ts("", "cp125l")


>>> b.decode(encoding="cp1251"), b.decode("cp1251")
('',

'')

n n str () :

>>> = bytes ("",


>>> str (, "1251")

"1251")

''

, n n bytes ,
n n, .

Windows-1251 KOI8-R, ( 6.5).

>>> w = ts("", "1251") # windows-1251


>>> k = w.decode("cp1251") .encode("koi8-r")
>>> k, str ( k, "koi8-r")
# KOIB-R
(b'\xf3\xd4\xd2\xcf\xcb\xc1', '')
> w = k.decode ("koi8-r") .encode ("1251")
>>> w, str(w, "1251")
# windows-1251
(b'\xd1\xf2\xf0\xee\xea\xe0', '')

6.1 3.

bytearray

n bytearray n bytes n
n. n

bytes, n bytearray n

n , n
n .

bytearray n:

n bytearray ( [<>,

<> [,

< >]]).

n , n . n

n bytearray, n n n.
n, TypeError.

109

> bytearray ()
bytearray(b' ')
>>> bytearray("cpoa", "1251")
bytearray(b'\xf1\xf2\xf0\xee\xea\xe0')
>>> bytearray ("")
Traceback (most recent 11 1ast):
Fi1e "<pyshe11#2>", 1ine 1," in <modu1e>
bytearray ("")
TypeError: string argument without an encoding
n

"strict" (n
UnicodeEncodeError; no ), "replace" (
n) "ignore" ( ).

>>> bytearray("string\uFFFD", "1251", "strict")


Traceback (most recent 11 1ast):
Fi1e "<pyshe11#5>", Hne 1, in <modu1e>
bytearray("string\uFFFD", "1251", "strict")
Fi1e "C:\Python32\lib\encodings\cp121.py", 1ine 12, in encode
return codecs.charmap_encode(input,errors,encoding_tale)
UnicodeEncodeError: 'charmap' codec can't encode character
'\ufffd' in position 6: character maps to <undefined>
>>> bytearray("string\uFFFD", "1251", "rep1ace")
bytearray(b'string?')
>>> bytearray("string\uFFFD", "1251", "ignore")
bytearray(b'string')

bytearray (<>), n n
255 n bytearray. nn
Va1ueError. :


n,

>>> = bytearray([225, 226, 224, 174, 170, 160])


>>>
bytearray(b'\xe1\xe2\xe0\xae\xaa\xa0')
>>> bytearray(b'\xe1\xe2\xe0\xae\xaa\xa0')
bytearray(b'\xe1\xe2\xe0\xae\xaa\xa0')
>>> str(b, "866")
''

bytearray (<>), n

. :

> bytearray(5)
bytearray(b'\x00\x00\x00\x00\x00')

bytearray. fromhex

(<>).

>>> = bytearray.fromhex(" 1 20 ")


>>>
bytearray(b'\xe1\xe2\xe0\xae\xaa\xa0')

110
>>> str (,

/.

Python 3

"866")

''

bytearray

, ( ):

>>>
>>>

bytearray("Python", "ascii")

[]

80

>>> [] = b"J"[O]
>>>
bytearray(b'Jython')

255.

bytes, , (b[OJ

b"J" [OJ ).

, , ,

n, .

append (<>) - .
. :

>>> = bytearray("string", "ascii")


> b.append(b"l"[O]);
bytearray (' stringl')

extend( <>) -

. . :

>>> = bytearray("string", "ascii")


>>> b.extend(b"l23");
bytearray(b'stringl23')
+ +=:

>>> = bytearray("string", "ascii")


>>> + b"l23"
#
bytearray(b'stringl23')
>>> += "456";
#
bytearray(b'string456')

, :

>>> = bytearray("string", "ascii")


>>> b[len(b) :] = b"l23"
#
>>>
bytearray(b'stringl23')

insert (<>,

n:

<>) - .

. .

1 :

>>> = bytearray("string", "ascii")


>>> b.insert(O, b"l"[O]);
bytearray(b'lstring')

111

insert () .

, .
:

>>> = bytearray ( "string", "ascii")


>>> [:] = b"l23";
bytearray(b'l23string')

( [<> J ) -

, ,

. , .
:

>>> = bytearray("string", "ascii")


>>> .()
#
103
>>>
bytearray(b'strin')
> .()
#

115

>>>
bytearray(b'trin')

>>> = bytearray("string", "ascii")


>>> del [5];
#
bytearray(b'strin')
> del [ :2];
#
bytearray(b'rin')

t remove (<>) -

del:

, .

ValueError.

. :

>>> = bytearray("strstr", "ascii")


>>> b.remove(b"s"[O]);
#
bytearray(b'trstr')

t reverse () -

~ . :

>>> = bytearray("string", "ascii")


>>> b.reverse();
bytearray(b'gnirts')

bytearray

decode ().

decode( [encoding="utf-8"] [, errors="strict"])

encoding ( UTF-8) bytearray,


errors- . errors

"strict"

( ),

n:

>>> = bytearray("cpoa", "cpl251")


> b.decode(encoding="cpl251"), b.decode("cpl251")
('',

'')

"replace"

"ignore".

112

/.

Python 3

_ str () :

>>> = bytearray("cpoa",
>>> str(b, "1251")

"1251")

''

6.14.

pick1e. ',
:

import pick1e
:

dnps (<>[,

<>][,

fix_imports=True])-

.
(

3).

>>> import pick1e


>>> obj1 = [1, 2, 3, 4, 5]
#
>>> obj2 = (6, 7, 8, 9, 10)
#
>>> pick1e.dnps(obj1)
b'\x80\x03]q\x00(K\x01K\x02K\x03K\x04K\x05e.'
>>> pick1e.dnps(obj2)
b'\x80\x03(K\x06K\x07K\x08K\tK\ntq\x00.'

1oads (<
>[,
fix _imports=True] [,
encoding="ASCII"] [,
errors="strict"])- n
. :

>>> pick1e.1oads(b'\x80\x03]q\x00(K\x01K\x02K\x03K\x04K\x05e. ')


[1, 2, 3, 4, 5]

>>> pick1e.1oads(b'\x80\x03(K\x06K\x07K\x08K\tK\ntq\x00. ')


(6, 7, 8, 9, 10)

6.15.

hashlib. n
, :

import hash1ib
:

md5 (), sha1 (), sha224 (), sha256 (), sha384 ()


sha512 ().
. :

>>> import hash1ib


>>> h = hash1ib.sha1(b"password")
n
:

update ().

113

>>> h = hashlib.shal()
> h.update(b"password")

di gest ()

hexdigest ( ) :

> h = hashlib.shal (b"password")


> h.digest ()
' [\xaaa\xe4\xc9\xb9??\x06\x82%\x0l\xf83\xlb-\xe\x8f\xd8'

>>> h.hexdigest()
'5baa6le4c9b93f3f0682250b6cf833lb7ee68fd8'
mctS (),

MD5.

, . .

.
, (

6.6).

!............ +! ................... . ...................._

................................................................................................................................................................................ .. . . _

........~................. .....................~

r ~.6. n napon

t ~ ~ -

....................~-

................... . ...................................-

........................ . ........................................................................... ~............-

,
...................................................... .............. ,

>>> import hashlib

> h = hashlib.mdS (b"password")


>>> = h.hexdigest()
>>>
# ,
'5f4dcc3b5aa765d6ld8327deb882cf99'
>>> h2 = hashlib.mdS(b"password")
# , n
> i f = h2. hexdigest () : print ( " n")

Python

re.

,
:

import re

7.1.

compile ().

<>= r.mil(<

~>[,

<>])

<.r.1> (

1 ):

+ L LOCALE- . ;
+ r IGNORECASE- . :
>>> import re
>>> = re.compile(r"~[a-]+$", re.I 1 re.U)
>>> print ("" if .srh("") else

"")

>>>
>>>

re.compile(r"[a-]+$",

print("Haeo"

if

re.U)

.srh("")

else

"")

ULTILINE- , ,

+ s

("\n").

OOTALL- "" ,

{\n).

""

. ~ ,
$ - . :

>>>
>>>

re.compile(r"~.$")

print("Haeo"

if p.search("\n") else

"")

7.

115

>>> = re . compile(r".$", re .M)


>>> print ("" if p.se.a rch("\n") else

"")

>>>
>>>

re.S)
if p.search ("\n" ) else

re . compile(r".$",

print("Haeo"

"" )

VEROSE- , n n
. , 1 n
. :

>>>

re.compile(r"""

(0-9)+ ( )
$
#
""", re.X 1 re.S)
> print("Haeo" i f p . search("1234567890") else "" )

>>> print ("" if p.search("abcd123") else

"")

u UNICODE- \w, \W, \, \, \d, \D, \s \S Unid


Python 3 no ;

ASCII- \w,

\w;

\, \, \d, \D, \s \S

, ~etrf , ,

r. , n .

, . n,

= re.compile (r"\w+$ " )

:
= . re.compile ("\\w+$")

~t

.,

,$,*,+,?,

{, [, ), \, 1,

( )

. ,
. n~ ,
. . ,
"" ~ , n
. ~ ,

( 1 . 1). n n
n (

7.1 ).

..

;t~~~~'!I..'""''"~"'~t'"""'''""t.'~t.,'~'"'''"'''''"'"'',.."'''H* , "'''''''''''''''"~'''"~"' " ''"'''''''~"'''"' '''''''''''''''''' ' ''' ' ''' ''''''''"''"'"'''C'"''""""'''-''"'"'"'''''''H'"'''''''''''""''' ' '".'"'''-~- "'1

~ 7.:1. f1& n~t

..

:,...,,._.,,",.,,,,,,,.,,,,\,,.,,,,,.,,.,,......~ .......,,.,.,,.,,,",,.,,,,,,,,,,,.,,,lo; .. .,,,,,,,,,,,,.,,,_,",,,,,,,.,.,,.,.,,,.,",._..........\l'h'ii..oo.,~. ............o...................... o1'; .:.......,.,;.,, ....... t .-....., ......: ....................,.,:,,u,,;,,,,,,,,,.,,,.,;

# -*- coding: utf-8 -*import re


"29,12. 2009"

re.compile(r"[0-3)

"\"

[0-9). [01) [0-9). [12) [09) [0-9 ) (0-9)$")

116

if p.search(d):
print ("
else:

")

print("aa

")

~:

'

/.

Python 3

re.compi1e(r"A[0-3] [0-9]\. [01] [0-9]\. [12] [09] [0-9] [0-9]$")


# "\"
if p.search(d):
print (" ")
e1se:
print (" ")
#

"\",

= re.compile(r"A[0-3] [0-9] [.] [01] [0-9] [.] [12] [09] [0-9] [0-9]$")
# ~
if p.search(d):
print (" ")
else:
print (" ")
# :
put ()

+ '(

( ( MULTILINE) S

DOTALL));

$ - ( ( MULTILINE) s
DOTALL));

+
+

\- ( );

\Z- ( ).

<> ( MULILINE),
, ,
.

(\n).
s

7.2).

"'''''''''''''"""~"''"'""'"'""'""'"''''''"''"'''"'""'"'''""'"''""'''".-.''"'""''""'''''"'''"'""""''"'"''""'"''''''"'""'''"''""''<'"""''"''"'"'''""''""'''""''"''"'"'''""'''''"'"'"'''''"'''"''"'"

7.2. .. n:tJJ ~r
'
;, ............................................ ;............. ;.. ;,,,,,,, ........ :...................................................................................................................................................................................................;
>>> = re.compile(r"A.+$")
#
>>> p.finda1l("strl\nstr2\nstr3") #

\n

[]

re.S) # \n
= re.compi1e(r".+$",
>>> p.finda1l("str1\nstr2\nstr3") #
['strl\nstr2\nstr3']
>>> = re.compile(r".+$", re.M) #
>>> p.findal1("str1\nstr2\nstr3") #
[ 'str1', 'str2', 'str3']

>>>

7.

117

n, n
.

n.

, (

7.3).

"'""''""'"'''"'""'''""'"'''''"'''"''"'"''''''"'''"''"''"'''"'""'''"""""''''"'''""'""''"'''''''"'''"""'"''"'''"""'''"'''"'"''"' ~":''.'''':.''.''"'''''''"''''"'''''''~"'".""'''''"':'','"'".''''''.''''"'''"''''''''''"''':

[. r7 .. ~ ~~ ~,Jiori> : f
.................. ............. ::... .............................::......... ,:.......... .....-::: ....:;.... ;.;,;;,;;:.........:;;::.....
;

# -*- coding: utf-8 -*import re

~;;;;~:

,i

... :.:.:...;,;,,,,;;;.;;'.:;-;;:.~ ........ ; ............ ;: ............ ;,,,,,;;,,;;;,,,,,,,;,

;,,,;,,,;~

......... ......................... ;
~

= re.compile(r"A[0-9]+$", re.S)
if p.searchi"245"):
print: ("")
# :
else:
print: (" " 1

if

p.search("Cpoa245"):

print
else:
print
input ()

("")

("

")

n , ,
, n "" (

# -*- coding: utf-8 -*import re

7.4).

= re.compile(r"[0-9]+", re.S)

if

p.search("Cpoa245"):

print
else:
print
input ()

("")

("

")

, n (

7.5) .

... ................. ,.. ,,,""'''''''"'"''

.,,.",,.,,,,", "

i...................
fl~~~~7.i.I1P~~R
"";,,,,,.,. .,;,,,""',..............
"""'

................................

'

# -*- coding: utf-8 -*import re


=

if

re.compile(r"[0-9]+$", re.S)
p.search("Cpoa245"):

print (" ")


else:
print (" ")
# :

1. .th 3

118

if

re.compile(r"[0-9]+",

re.S)

p.search("Cpoa245"):
print.("Ec

else:
print ("
# :
input ()

")

")

[J

. :

+
+
+
+
+

[09] - 9;
[0-9] - 9;
[] - "", "" "";

[-] - "", "", "" "";


[-R] - "" "";

[] - "", "" "";

[-] - "" "";

+
+

[-R-] - ;

[0-9-R--z-Z] - .
!
""

[a-R].

, .

, :

(09] - 9;

+
+

[-9] -

9;

[-R--z-Z] - .

, ,
. , ,
(,

- ).

-,

, .
,

\.

+
+

\d-

. (S) [0-9];

\w- , .
(ASCII) [a-zA-Z0-9 _J;

\ s -
[ \t\n\r\f\v];

\D- . (ASCII) [-9];

(ASCII)

7.

119

\W- , . rip (ASCII)


r~a-zA-Z0-9

J;

\S-
r~ \t\n\r\f\v].

(s)


Pytho

. ,

\d

u (UNICODE).

, Uicode,
, ,

\s

\w

i .

,
.

r!mzurjnu,amopo:

. . "[-9]

{n}- n

{2}$"

{n,}-

n . .

r"A [0-9] {2, }$"

{n,m}-

m . IICJiil
r" ,, [ -9 J 12, 4 J $"

. ,

* -

{0, };

+- .

{1' };

? - . J 11 {0, 1}.

"". 1
, , i1 .
. <>, J\1:

>>> s = "<b>Textl</b>Text2<b>Text3</b>"
>>> = re.compile(r"<b>.*</b>", re.S)
>>>

p.fidall (s)

['<b>Textl</b>Text2<b>Toxt3</b>']
11 . "

", ? (iii

7.6).

[. 7.6. ''"
....; ...............:................. ......;.............. ........................................................... ..................... ..................................................... .
~

>>> s = "<b>Textl</b>Text2<b>Text3</b>"
>>> = re.compile(r"<b>.*?</b>", re.S)
> p.findall (s)
[ '<b>Textl </>', '.<b>Text3</b>']
, . ~ riO.'IY'IIII. ~ ,

7.7).

11

7.

121

. .
u

e-mail

?P<name>. n

7.1 0) .

...... ,.......................................; .......... ;;,,,;;;~ ................ ;,,,;,;,,,;;;~ ... ;.;,,,,,;,, .. ,,,,;,,;;.... ; .....;,;,:,,,;,;; ..........................,;;,,;.;................:.,;;.. :..:................................

>>> email = "test@mail.ru"


>>> = re. compile ( r'"'" ( ?P<name> [a-z0-9 . -] +) #
@
#
(?P<host>(?: [a-z0-9-]+\.)+[a-z] {2,6}) #
""", re.I 1 re.VERBOSE)
>>> r = p.search(email)
>>> r.group("name")
#
'test'
>>> r.group("host")
#
'mail.ru'

H@ll

, n
:
(

(?P=name) . . n n n

7.11 ).

~;;-~~;~~ti1~~c;~iii~~a~:~~ii~~g~~~~~;'~~~~~~~:~'kY+~~ili~~~g~~

;,;;,,,; : :.. ;; ..................;;,, ~.:.;~.;,;;,;;;.,,,,.,;.;;;'i ;;.-.::.:~ . ;;;;;-,;,;;:;,:,, '.;.;,;;,;';,,,;.;,,,,,,,;,... ;:.' ;',;;;;;...... ;,;.~;;;;.'.;;;,,;; .. ;; ..=;;;;,.;;,,,;~ .:~;;.'.~;;;:~;,;;;,;; .. ;,;; .. ;,.;,,,.;,,;.. : .

>>> s = "<b>Textl</b>Text2<I>Text3</I>"
> = re.compile(r"<(?P<tag>[a-z]+)>(.*?)</(?P=tag)>", re.S
> p.findall (s)
[ ( '' , 'Text 1 ' ) , ( ' I ' , 'Text 3 ' ) ]

............................... .

re.I)

, u:

(?aiLmsux)- n nu . "", "i", "L",

"m", "s", "u"


u

+
+

"" ,

compile ();

(?# . ) -. ;

(?= ...

)-n n n. , n n

n:

>>> s = "textl, text2, text text4"


>>> = re.compile(r"\w+(?=[,])", re.S
> p.findall (s)
[ 'textl', 'text2']

(?! ... ) -

re.I)

u n n. , n

n:

>>> s = "textl, text2, text text4"


> = re.compile(r"[a-z]+[0-9] (?! [,])", re.S
> p.findall (s)
[ 'text', 'text4']

re.I)

(?<= ... ) -n n . , n n
n n:

122

/.

Python 3

>>> 5 = "textl, text2, text text4"


> = re.compile(r"(?<=(,] ( ]) [a-z]+[0-9]", re.S 1 re.I)
> p.findall (s)
( 'text2', 'text']

+ (?<! ... ) -

. . ,

, :

>>> 5 = "textl, text2, te~t text4"


> = re.compile(r"(?<! (,]) ((a-z]+(0-9])", re.S 1 re.I)
> . findall (5)
('text4']

(? ( id

name) l11j!2) -

. ,

l,

2. ,

. , :

>>> s = "textl 'text2' 'text text4, text5"


> = re.compile(r"(')?([a-z]+(0-9]) (?(1) '1,)", re.S 1 re.I)
> p.findall (5)
1
1
[ ("
",
text2 1 ) , ( 1 1 , 1 text4 1 ) J
. , ,
, :

>>> 5 = "-wordl -word2 -word -word4 -word5"


>>> re.findall(r"\5\-((a-z0-9]+)\5", s, re.S 1 re.I)
1
(
word2 1 , 1 word4 1 ]
, .
, . . .

, ( 1\5)

(\51$) .
, ? : :

>>> re.findall(r"(?:l\s)\-((a-z0-9]+){?:\sl$)", s, re.S 1 re.I)


1
(
wordl 1 , 1 word 1 , 1 word5 1 ]
.

"word2"

"word4"

? ' .
, .
, . . , .
, :

"-wordl

<>-wrd2

-word

-word4 -word5"

"-word2" ,

. "word",
:

"-wordl -word2

-word

<>-wrd4

-word5"

"-word4" , .

"word2"

"word4"

"word5",

, . .

naf}a

7.

123

. ,

(?= ... ) :

> re.findall(r"(?:l\s)\-((a-z0-9]+)(?=\si$)", s, re.S


['wordl', 'word2', 'word', 'word4', 'word5']
1 .

(?:\si$)

re.I)

(?=\sl$).

nn .

7.2.

n n :

+ match ()

. :

match(<Cpoa>[,

< >[,

< >]])

Match,

None. :

>>> import re
> = re.compile(r"[0-9]+")
' >>> print("Haeo" if p.match("strl23") else

"")

>>>

print("Haeo"

if p.match("strl23", 3) else

"")

>>>

print.("Haeo"

if p.match("l23str") else

"")

match () match () . :
re.match(<lliao>,

<>[,

<>])

<>

. <> ,

compile (). ,
None. :

Match,

>>>
>>>

= r"[0-9]+"

print("Haeo"

if re.match(p, "strl23") else

"")

print("Haeo"

if re.match(p, "123str") else

"")

= re.compile(r"[0-9]+")
if re.match(p, "123str") else

"")

>>>

>
>>>

print("Haeo"

search () -

. :

search(<Cpoa>[,

<

>[,

< >]])

, atch,

>>>
>>>

None.

= re.compile(r"[0-9]+")
if p.search("strl23".) else

print("Haeo"

"")

124
>>> print

(""

if

search ( "123str") else

1.

Python 3

"")

>>>

print("Haeo"

if p.search("l23str", 3) else

"")

search () search (). :

r.srh(<>,

<>[,

<>])

n <>

. <> ,
n

compile (). ,
None. :

Match,

>>>
>>>

= r"[0-9]+"

if re.search(p, "strl23") else

"")

= re.compile(r"[0-9]+")
if re.search(p, "strl23") else

"")

print("Haeo"

>
>>>

print("Haeo"

n (.

4.16)

, , , n
(

7.12).

, n .

# -*- coding: utf-8 -*import re


print (" 'stop' ")
sumna =
= re.compile(r"[-]?[0-9]+$", re.S)
while True:
= inut(" : ")
= x.rstrip("\r")
# 3.2.0 (.
if == "stop":
break
#
if not p.search(x):
print (" , !")
continue #
= int(x)
#
sumna +=
print("Cya :", sumna)
input ()

Match,

()

match ()

1.7)

search (),

r e - n ,
search (). :
n ;

groups-

groupindex-

()

match ()

+
+
+
+
+

7.

string-

125

<> ()

match ()

search ();

pos '--- < n> match () search ();


endpos

- < n>

match ()

lastindex-

lastgroup-

search () ;

None;
None.

>
re.compile(r"(?P<num>[0-9]+) (?P<str>[a-z]+)")
>>> m p.search("123456string 67890text")
>>> m
< sre.SRE Match object at Ox00FC9DEB>
>>> m.re.groups, m.re.groupindex
(2, { 1..11\ : 1, 1 Str 1 : 2})
>>> p.groups, p.groupindex
(2, { 1 num 1 : 1, 1 Str 1 : 2})
>>> m.string
1
123456string 67890text 1
>>> m.lastindex, m.lastgr'oup
(2, Str')
>>> m.pos, m.endpos
(0, 22)
1

group ( [ <id1

name1> [, ... , <idN

nameN> JJ) -

. ,
, . .
, , .

. ,
, .
,

IndexError.

> = re.compile (r" (?P<num> [0-9] +) (?P<str> [a-z] +) ")


>>> m = p.search("123456string 67890text")
>>> m.group(), m.group(O) # 6
1
(
123456strinGJ 1 , 1 123456string 1 )
> m.group(1), m.group(2)
#
1
(
123456 1 , 1 string 1 )
>>> m.group("num"), m.group("str") #
1
(
123456 1 , 1 String 1 )
>>> m.group(1, 2), m.group("num", "str") # n
1
((
123456 1 , 1 String 1 ) , ( 1 123456 1 , 1 String 1 ) )

groupdict ( [<

> J )

. ,

None,

, :

> = re.compile(r"(?P<num>[0-9]+) (?P<str>[a-z])?")


> m = p.search("123456")
>>> m.groupdict()
1
{
num': 1 123456 1 , 1 Str 1 : None}
>>> m.groupdict("")
1
{ um :
123456 1 , 1 Str 1 : " }
1

126

groups ( [< > J ) -

1.

Python 3

. ,
None, , :

>

>>> m

re.compile(r"(?P<num>[0-9]+) (?P<str>[a-z])?")
p.search("123456")

>>> m. groups ()
(' 123456', None)
>>> m.groups("")
('123456',

')

start ( [< >]) -

, ,

- . ,

-1;

end ( [< >]) -

, ,
- . ,

-1;

span ( [< > J) -

. . ,
, - .
, (-1, -:1). :

>>>

re .compile (r" (?P<num> [0-9] +) (?P<str> [a-z] +) ")

>>> s = "str123456str"
>>> m = p.search(s)
>>> m.start(), m.end(), m.span()
(3, 12,

(3, 12))

>>> m.start (1), m.end(1), m.start ("num"), m.end("num")

(3, 9, 3, 9)
>>> m.start(2), m.end(2), m.start("str"), m.end("str")
(9, 12, 9, 12)
>>> m.span(1), m.span("num"), m.span(2), m.span("str")
( (3, 9)' (3, 9)' (9, 12)' (9, 12))
>>> s[m.start(1) :m.end(1)], s[m.start(2) :m.end(2)]
('123456',

'str')

expand 1<>) -

: \, \g<> \g<>.
:

>

re.compi1e(r"<(?P<tag1>[a-z]+)><(?P<tag2>[a-z]+)>")

>>> m = p.search("<br><hr>")
>>> m.expand(r"<\2><\1>")
'<hr><br>'

>>> m.expand(r"<\g<2>><\g<1>>")

\g<>

'<hr><br>'
>>> m.expand(r"<\g<tag2>><\g<tag1>>") # \g<>
'<hr><br>'
search 1) ,
, (

7.13).

7.

127

r''"''::"'""""'''.'''""'"''''"''''"''"''''''""'''~''''"''"'''''::::.''".'''"'''''':':~:::"'':""'''.:::.~.''''''"''"''~"':'.''"""'::'"''"''''''':'.'''''''.'''''''''''"''''''''.'''''.''''''~'"~''"''''''''''''''''''"'''''''"''

.......................................................................................:.; ................:;.......:.................::......... ....... :.....................................:...................................;.. , ...... :.... .


;

# -*- coding: utf-8 -*import re


email = input (" e-mail: "1
email = email.rstrip("\r")
# 3.2.0 (.
= r'([a-z0-9 .-]+)@(([a-z0-9-]+\.)+[a-z]{2,6))$"
= re.compile(pe,
re.I 1 re.S)
m = p.search(email)
if not m:
print ( "E-mail "}
else:
print("E-mail", m.group(O), " ")
prlnt("w:", m.group(l),
":", m.group(2))

1.7)

put(l

n:

e-mail: user@mail.ru

E-rnai1 user@mail.ru
: user : mai1.ru

7.3.

n n n .

f idall ( 1 n . :

finda11(<Cpoa>[,

<

>[,

< >]]}

, n , n
n n. nn,
n , . :

> import re
> = re.compi1e(r"[0-9]+")
>>> p.finda11("2007, 2008, 2009, 2010, 2011"1
['2007', '2008', '2009', '2010',
= re.complle(r"[a-z]+")

>
>

. fida11

'2011']

( "2007, 2008, 2009, 2010, 2011" 1

[]

> t = r"(([0-9]{3})-([0-9]{2}}-([0-9]{2}))"
> = re.compile(t)
> p.findal1("322-77-20, 528-22-98")
[('322-77-20',
('528-22-98',

'322',
'528',

'77',
'22',

'20'),
'98')]

finda11 ( 1 n fidall ( J. :

re. findal1

(<>,

<>

[,

<>]

n <> n
. n <> , n
compi 1 ( 1.

128

/. Python 3

>>> re.finda11(r"[0-9]+", "1 2 3 4 5


['1',

'2',

'3', '4', '5',

>>> = re.copile(r"[0-9]+")
>>> re.finda11 (, "1 2 3 4 5
'2',

['1',

'3', '4', '5',

")

'6']
")

'']

finditer () findall (), , .


Match. :


finditer(<Cpoa>[,

< >[,

< 3>]])

> =
> for

2007
2008
2009
2010
2011

re.copile(r"[0-9]+")

in p.finditer("2007, 2008, 2009, 2010, 2011"):


print (.group(O), "start: ", .start (), "end: ", .end())

start: end: 4
start: end: 10
start: 12 end: 1
start: 18 end: 22
start: 24 end: 28

finditer () finditer (). :

re.finditer(<ao>,

<>[,

<>])

<>

. <> ,
i1

().

>>> = re.copi1e(r"<b>(.+?)</b>", re.I


>>> s = "<b>Text1</b>Text2<b>Text3</b>"
>>> for in re.finditer(p, s):

re.S)

print(.group(1))

Text1
Text3

7 .4.

sub () .

, . :

sub (<: >,


[, < >])

< >

\,

\g<>

\g<>, .
:

>>> import re
> = re.copile(r"<(?P<tag1>[a-z]+)><(?P<tag2>[a-z]+)>")

7.

129

>

p.su (r"<\2><\1>", "<br><hr>")


#
'<hr><br>'
> . sub (r"<\g<2>><\g<1>>", "<br><hr>")
#
'<hr><br>'
> p.su(r"<\g<tag2>><\g<tag1>>", "<br><hr>") #
'<hr><br>'

\g<>

\g<>

n Match, . ,
, .
10:

# -*- coding: utf-8 -*import re


def rep1 (m) :
""" . m = int(m.group(O))
+= 10
return "{O}".format(x}

= re.compi1e(r"[0-9]+")

print(p.su(rep1,

Match """

"2008, 2009, 2010, 2011"))

priht(p.su(rep1,

"2008, 2009, 2010, 2011", 2))

input ()
:

2018, 2019, 2020, 2021


2018, 2019, 2010, 2011

BHHMAHHEI
.

su () . su (). :
r.su(<>,

< >,

< >[,

< >

[, flags=O]])
<>

n . ,
:

# -*- coding: utf-8 -*import re


def rep1 (m) :
""" . m- Match """
tag1 = m.group("tag1") .upper()
tag2 = m.group ( "tag2"). upper ()
return "<{0}><(1)>".format(tag2, tag1)
5 . 1349

130

/.

Python 3

= r"<(?P<tag1>[a-z]+)><(?P<tag2>[a-z]+)>"
rep1, "<br><hr>"))
input ()

print(re.su(p,

<HR><BR>
sun

1)

sub 1),

- .

(
[,

sun <i'r

<

i<>,

<

>

>])

>>> = re.compi1e(r"[0-9]+")
>>> p.subn("O", "2008, 2009, 2010, 2011")
('0,

0', 4)

sun

1)

r.sun(<>,

<

- sun

>

[,

11: :

i<>,

<

>

[, flags=O]])
<>
. :

>>> = r"200[79]"
>>> re. sun (, "2001", "2007, 2008, 2009, 2010")
('2001, 2008,2001, 2010', 2)

7.5.

split 1) .

, .
, ,

. :
s1it(<

>[,

<>])

>>> import re
>>> = re.compi1e(r"[\s, .]+")
>>> p.sp1it("word1, word2\nword3\r\nword4.word5")
['word1', 'word2', 'word3', 'word4', 'word5']
>>> p.sp1it("word1, word2\nword3\r\nword4.word5", 2)
[ 'word1', 'word2', 'word3\r\nword4. word5']
, ,
:

>>> = re.compi1e(r"[0-9]+")
>>> p.sp1it ("word, word\nword")
['word, word\nword']

7.

131

split () split (). :


re.split(<ao>,

< >[,

<>[,

fla9s=O]])

<>
. :

> = re.compile(r"[\s, .]+':)


> re.split(p, "wordl, word2\nword3")
[ 'wordl', 'word2', 'word']
> re.split(r"[\s,.]+", "wordl, word2\nword3")
[ 'wordl', 'word2', 'word']

escape (<>)

, .
. :

> print(re.escape(r"[] () .*"))


\[\]\(\)\.\*

:- .
. n n
n n n .
. ,
,

1.

n n n .
n, n , n ,

(n+), n (n*), n (n

in).

n n . , n
, :

>>> arr = [1, 2, 3]


>>> arr[O]
1
>>> arr[O]
50
>>> arr
[50, 2, 3]

#
#

n . , n
, :

>>> t
> t

(1, 2, 3)

[0]

#
#

> t[O] =50


#
Traceback (most recent call last) :
File "<pyshe11#7>", line 1, in <module>
~[0] =50
#
TypeError: 'tuple' object does not support item assignment

'

n n.

8.1.

n n.:

list ( [<>]). n n

n . , n n.

133

':

> 1ist ()

[]

>>> 1ist("String")
#
['S', 't', 'r', 'i', 'n', 'g']
> 1ist ( (1, 2, 3, 4, 5))
#

[1, 2, 3, 4, 5]

n :

>>> arr = [1, "str", 3, "4"]


>>> arr
[1, 'str', 3, '4']

+ n n n n append ():
>>>
>>>
>>>
>>>
[1,

arr = []
arr.append(l)
arr. append ( "st r")
arr
'str']

#
#
#

0)
1)

n (n, ) ,
n n .

Python n n :
> arr = [)
> arr[] = 10
SyntaxError: inva1id syntax
> arr[O] = 10
Traceback (most recent +1 last):
File "<pyshell#20>", 1ine 1, in <modu1e>
arr[OJ = 10
IndexError: list assignment index out of range
n n , .
n nn n. nn n
.n , n . n:

>>>
>>>

=
,

[1, 2]

( [1, 2],

[1, 2])

n n n n

. n nn n :

> y[l] = 100


>>> ,
( [1, 100], [1, 100])

#
#

n, n n
n . , n

, . n , n
n:

134
>>>
>
>>>

[1, 2]'
100

[1]
,

/.

Python 3

[1' 2]

1 [ 1' 2] '

[ 1' 100] )

n n n n

*.

n,

n nn n n
n ~:

> arr = [ [] ] * 2
>>> arr
[ []'

#
#

[]]

>>> arr[O] .appendl5)


>>> arr
[ [5]'

[5]]

n n

append 1)

>>> arr
[]
>>> for i in rangel2): arr.appendl[])
>>> arr
[ []'

[]]

>>> arr[O] .appendl5); arr


[ [5]'

[]]

n :

>>> arr = [ [] for i in rangel2) ]


>>> arr
[ []'

[]]

>>> arr[O] .appendl5); arr


[ [5]'

[]]

, nr , n n is.
n , n is

True:
>>> = = [1, 2]
#
>>> is # m
True
>>> ,
[1, 2], [1, 2] #
>>> is
#

F'alse
1 , n n ,
. , n n? n
n n

, n-

1ist 1) ( 8.1 ).

.....................................................................;..,,;,,,;;. :.......;.;..;;;....;,;,,,,;;. ,, ....


>>> = [1, 2, 3, 4, 5] #
>>> #
>>>=

listlx)

~;;;,;:,;;,

............,... ,, ..,.... ,,.,,,

= [:]

>>>

8.

[1, 2, 3,

>>>

135

is

4, 5]

False
>>> [1]
100 #
>>> ;.;,
#
( [1, 2, 3, 4, 5]' [1, 100, 3, 4, 5])

, .

is

, .
. ,

Python
>
>

>>>

. :

= [1, [2, 3, 4, 5]] #


= 1ist ()
#
lS
#

False
> [1] [1]
>>>

100

#
#

( [1, [2, 100, 4, 5] J' [1,

! 1 1

[2, 100, 4, 5] J)

,
.
,

is

1ist {)

, ,

. . ,

1ist ()

,
(

deepcopy ()

8.2).

"!'"''""""'"'.''""'''''""'""""""''"'''""'''""''''""''"'''-'"'"'''"''"''''""'""""'""'''''"'

f..P~~~~~--~:~~.?..~~~-~::~~~~-~~:~,1.q~-~-~~~,~~-,:~.,,,,
>>> import

>

[1,

[2,

3,

4,

[1]

>>>

( [1, [2, 3, 4, 5] J'

deepcopy {)

5]]

= copy.deepcopy{x)
[1] = 100

>>>

>

... .

[1,

#
#
#
[2, 100, 4, 5] J)

. , .

, ,
, . :

> import
> = [1, 2]
> = [, ]
>>>

[ [ 1, 2]' [1, 2 J J
>>> z = copy.deepcopy{y) #

> z [0] is , z [1] is


{Fa1se, Fa1se, True)

z [0] is z [1]

136
> z[O] [0] = 300
>>> z.
[ [ 300, 2] , [ 300, 2] ]
>>>

#
#

/.

Python 3

[ 1, 2]

8.2.

,
. .
:

>>> arr = [1, "str", 3.2, "4"]


>>> arr[O], arr[1], arr[2], arr[3)
( 1, 'str', 3. 2, '4')

- . =

, :

>>>
>>>

z
z

[1, 2, 3] #

( 1, 2, 3)

>>> , = [1, 2, 3]
#
Traceback (rnost recent call last):
F'ile "<pyshe11#86>", line 1, in <rnodule>
, = [1, 2, 3]
#
Va1ueError: too n va1ues to unpack (expected 2)

Python 3

= . ,
"" . , :

>>> , , *z
[1, 2, 3]; , , z
(1, 2, [3])
>>> , , *z = [1, 2, 3, 4, 5]; ,
(1, 2, [3, 4, 5])
>>> , , *z
[1, 2]; , , z
(1, 2, [])
>>> *, , z = [1, 2]; , , z
( [], 1, 2)
>>> , *, z = [1, 2, 3, 4, 5]; ,
(1, [2, 3, 4], 5)
>>> *z, = [1, 2, 3, 4, 5]; z
[1, 2, 3, 4, 5]

,
.

len ():

>>> arr = [1, 2, 3, 4, 5]


>>> len(arr)
#
5

>>> arr[1en(arr)-1]

137
#

5
, , ,

IndexError:

>>> arr = [1, 2, 3, 4, 5]


>>> arr[5]
#
Traceback (most recent 11 1ast):
Fi1e "<pyshell#99>", 1ine 1, in <modu1e>
arr[5]
#
IndexError: 1ist index out of range

, ,
, :

>>> arr = [1, 2, 3, 4, 5]


>>> arr[-1], arr[1en(arr)-1]

(5, 5)
,
:

>>> arr = [1, 2, 3, 4, 5]


> arr [0] = 600
>>> arr

[600, 2, 3, 4, 5]
, ,
. :
[<>:<>:<lli>]

. <> ,
. <> ,

. , , ,
. <> ,
.
. . :

>>> arr = [1, 2, 3, 4, 5]


>>> m = arr[:]; m #

[1, 2, 3, 4, 5]

>>> m is arr
Fa1se

is

~,

>>> arr = [1, 2, 3, 4, 5]


>>> arr[::-1]
#

-1

[5, 4, 3, 2, 1]
:

> arr[1: J
[2, 3, 4' 5]

1.

138
> arr[:-1]

/.

Python

[1, 2, 3, 4]
:

> arr[0:2]

[1, 2]
:

> arr[-1:]

[5]
, , :

>>> arr[1:4] #

1, 2

[2, 3, 4]
. ,
, , :

>>> arr = [1, 2, 3, 4, 5]


>>> arr[1:3] = [, 7] #
>>> arr

[1,

7, 4, 5]

>>> arr[1:3]
>>> arr

[]

[1, 4, 5]
+.
:

arr1
[1, 2, 3, 4, 5]
arr2
[, 7, 8, 9]
arr3
arr1 + arr2
arr3
[1, 2, 3, 4, 5, , 7, 8, 9]

>>>
>>>
>>>
>>>

+ +=. ,
:

>>>
>>>
>>>
[1,

arr = [1, 2, 3, 4, 5]
arr += [, 7, 8, 9]
arr
2, 3, 4, 5,

7, 8, 9]

,
. *,

>>> [ 1, 2, 3] * 3

#
[1, 2, 3, i, 2, 3, 1, 2, 3]
>>> 2 l [ 1, 2, 3, 4, 5], in [1, 2, 3, 4, 5] #
(True, Fa1se)

in:

8.3.

8.

139

. ,
, , , , . .
, , :

> arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]


, .
, :

>>> arr = [

[1, 2, 3]'
[ 4' 5, ]'
[7, 8, 9]

, :

> arr[1] [1]


5
.

. ,
. .
:

>>> arr = [ [1,

> arr[O] [1]

["",

""],

3],

[4, 5, 6],

[7, 8, 9] ]

[]

''

>>> arr = [ [1,

> arr[O] [1]


1

[""]

"":

10,

"":

["s", 5] } ] ]

[0]

8.4.

for:

>>> arr

[1, 2, 3, 4, 5]

>>> for i in arr: print(i, end=" ")


:

1 2 3 4 5
, i ,
(, ),
:

>>> arr

[1, 2, 3, 4]

()

>>> for i in arr: i += 10


>>> arr

[1, 2, 3, 4]
>>> arr
[ [1' 2]' [3, 4] ] #
>>> for i in arr: i [0] += 10

()

140
>>> arr
[ [11, 2]'

/.

Python 3

[13, 4]]

n n , , n, n

range () . , .
for n .
range () :

range ( [<>, ] <> [,

<>]

n . n <> ,
n . n .

, n .
n <> , n

arr = [1, 2, 3, 4]
for i in range(1en(arr)):
arr[i] *= 2
print (arr)

1.

2:

for

[2, 4,

8]

enumerate (<> [, start=OJ),

. n

arr = [1, 2, 3, 4]
for i, elem in enumerate(arr):
arr[i] *= 2
print (arr)
#

2:

[2, 4,

8]

, n n

while.
while for.
n 2, n. while:
n,

arr = [1, 2, 3, 4]
i, = , len(arr)
while i < :
arr [i] *= 2
i

+= 1

print (arr)

8.5.

[2, 4,

8]

-
n n :

arr = [1, 2, 3, 4]
for i in range(len(arr)):
arr[i] *= 2
print(arr)

m:

[2, 4,

8]

n n n n.
n n
n n:

for.

8.

141

arr = [1, 2, 3, 4]
arr = [ i * 2 for i in arr ]
print (arr)
#

m:

for

[2, 4,

8]

: , ,

. ,
. ,

.
, .
. ,

for

()

if

1:

arr = [1, 2, 3, 4]
arr = [ i * 10 for i in arr if i % 2 == ]
print (arr)
# m: [20, 40]

:

arr = []
for i in [1, 2, 3, 4]:
i f i % 2 == 0:
arr.append(i * 10)
print (arr)

#
#
#


m:

[20, 40]

1:

arr = [[1, 2], [3, 4], [5, 6]]


arr = [ j * 10 for i in arr for j in i if j % 2 ==
print(arr)
# m: [20, 40, 60]

:

arr = []
for i in [ [1, 2], [3, 4], [5, 6]]:
for j in i:
if j % 2 == 0:
#
arr.append(j * 10) #
print (arr)
# m: [20, 40, 60]
, ,
, .
. :

>>> arr = [1, 4, 12, 45, 10]


>>> sum( ( i for i in arr if i % 2
26

8.6.

(),

==

) )

zip(), filter()

reduce()

map ()
. :
m(<>,

<!>[,

... ,

<N>])

142

map ()

Pytln

/.

Python 3

, n , n,

2.

n n Pytl11

3,

1ist ().

<> (
), n n.
.
n

10

: ... : .. '. : .... .,' ...... :: :: .: ......... : .: ... .; :. .. ''': :-: :.": :- .... :-.
[ I, :~., ()
':"

8.3).

~. ~.

def func (e1em) :


"""
return e1em + 10 #
arr = [1, 2, 3, 4, 5]
print( 1ist( map(func, arr) ) )
# : [11, 12, 13, 14, 15]

map ()

n n.

n , n n
.

n (

8.4 ).

def func(e1, 2, 3):


"""
return 1 + 2 + 3 #

"""

arr1
[1, 2, 3, 4, 5]
arr2
[10, 20, 30, 40, 50]
arr3
[100, 200, 300, 400, 500]
print( 1ist( map(func, arr1, arr2, arr3) ) )
# m: [111, 222, 333, 444, 555]
n ,

n :

def func(e1, 2, 3):


"""
return 1 + 2 + 3

"""

arr1
[1, 2, 3, 4, 5]
arr2
[10, 20]
arr3
[100, 200, 300, 400, 500]
print( 1ist( map(func, arr1, arr2, arr3) ) )
# m: [111, 222]

zip ()

n, n . -

8.

143

, n , n,
n n

Python 3,

Python 2.

n list

1).

zip 1<l> [,

... ,

<N>]

> zip([1, 2, 3],

[4, 5, 6], [7, 8, 9])


<zip object at Ox00FCAC88>
> list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
[(1, 4, 7),

(2, 5, 8),

(3,

6,

9)]

n , nn
,

> list(zipl[l, 2, 3], [4, 6], [7, 8, 9, 10]))


[(1, 4, 7),

,2,

6, 8;]

n n n (
n n

....................... ............. ,.................... ,..... .


( 8~5. ~.

; ,:, ,.;;,:.:,; .~..... : ... ''. : . i ,;,,; .:. ; ' ............................. ' ... ' ...

[1, 2, 3, 4, 5]

arr2
arr3

[10, 20, 30, 40, 50]


[100, 200, 300, 400, 500]

+ z for

(,

filter

1)

8.5) .

....-.-
.......
.
.

arr1

"~ !l> zip ()

:.. .>......... : .................................................. ",,,,.,,;,;,,;,,,,.;;;,,.

arr = [ +
print (arr)

8.4)

zip 1) map 11 (

z) in zip(arrl, arr2, arr3)]

[111, 222, 333, 444, 555]

n n n n.

:
filtr(<>,

<>)

n n None,
n n True.
False,
. , n , n

Python 2.

> filter (None, [l,

list

None,

n n

1).

Python 3,

[], 2])

<filter object at Ox00FD58BO>


> list (filter (None, [l, , None,

[], 2]))

[ 1' 2]
n n n :

> [ i for i in [l,

None,

[], 2] if i ]

[ l' 2]
n n . n
n n. -

144

True,

filter 1)

Python 3

n -

n (

/.

False.

8.6).

\ 8.6. n -cr1ori3b~.~
:.................~ ......................... ;;..... :... ..........:~ ....:.::........:,,;;; ;;.;. ::~;~ ..~.
def func (e1em) :
return e1em >=

arr = [-1, 2, -3, 4, , -20, 10]


arr = 1ist(fi1ter(func, arr))
print larr)
# n
arr = [-1, 2, -3, 4, , -20, 10]
arr = [ i for i in arr if func(i) ]
printlarr)

reduce 1)

functoo1s

[2, 4,

10]

[2, 4,

10]

n n

n . :
rdui<>,

<>[,

<

>])

n n .
n , -
. n (
..

..

8.7).

..

''~"''"'"'''"'''' "''"" ""'''''~~~~.'.''".'.".~~.'.'.'.'.~.'.'.'.' .'.'''~.''.'.'.~'.'".".'.''.'.~.''"'""'.'""'''~~.'.~~....~~.''"~''''~''"""'''-'''"''.'~~.'.'""''"'"""''''''"'~"''"''"""".''''""''""""''''"'"""""'''"'"""""""""""''''"''"'"'"'''""'''";,',

l:.................................................................
8.7 ~nj"i~~tt"~i"~~~~()
.;:.::.............. ;;..

....,. ....
,,;,,.';;,,,;,;;~

from functoo1s import reduce #

:.;.',;~;;'Ji:.;=; ;);.~;;

::.:;;;;,;~;;;;~;;,;;;;.:;,:.:.~~.:.;;:~... ;::;,; .. ,...... ;,,;,;,;~; .......................... :.......... "'"''""''"''""'';.......... ;

def func (, ) :
printi"I{O}, {1})".formatlx,
-return +

),

end=" ")

arr = [1, 2, 3, 4, 5]
summa = reducelfunc, arr)
#: (1, 2)
(3, 3) 16, 4) 110, 5)
printlsumma) # : 15
summa = reducelfunc, arr, 10)
# : 110, 1) 111, 2) (13, 3) (16, 4)
printlsumma) # m: 25
summa = reduce 1func, [], 10)
printlsumma) # m: 10

8.7.

(20, 5)

n n :

append 1<>) -

n.

n .

8.

145

>>> arr = [1, 2, 3]


>>> arr.append(4); arr

arr

>>> arr.append((7, 8)); arr

[1, 2, 3, 4]

>>> arr.append([5,
[1, 2, 3, 4,
[1, 2, 3, 4,

]);

]]

[5,

],

[5,

(7, 8)]

extend (< >) -

. . :

>>>
>>>
>>>
>>>
>>>
[1,

arr = [1, 2, 3]
arr .extend ( [ 4, 5, ])
arr. extend ( (7, 8, 9))
arr. extend ( "")
arr
2, 3, 4' 5, , 7, 8, 9,

#
#
#
'',

'',

'']


+=:

>>>
>>>
[1,
>>>
>>>
[1,

[1, 2, 3]
arr
arr + [ 4, 5, ]
2, 3, 4' 5, ]
arr += [ 4' 5, ]
arr
2, 3, 4' 5, ]

, :

>>> arr = [1, 2, 3]


>>> arr[1en(arr) :]
>>> arr
[1, 2, 3, 4, 5,

[4, 5,

insert (<>,

<>) - .

. .

>>>
>>>
[0,
>>>
[0,
>>>
[0,
>>>
[0,

arr = [1, 2, 3]
arr.insert(O, 0); arr
#
1, 2, 3]
arr.insert(-1, 20); arr #
1, 2, 20, 3]
arr.insert(2, 100); arr # 100
1, 100, 2, 20, 3]
arr.insert(10, [ 4' 5]); arr #
1, 100, 2, 20, 3, [4, 5]]

insert () .

, .
:

/.

146

Python 3

>>> arr = [1, 2, 3]


>>> arr[:O]
[-2, -1, 0]
>>> arr
[-2, -1,

1, 2, 3]

( [<>] ) -

erd.

, ,

, .

IndexError. :
>>> arr = [ 1, 2, 3, 4' 5]
>>> arr.pop()
# n n
5
>>> arr
# n
[1' 2, 3, 4]
>>> arr.pop(O)
# n n
1
>>> arr
# n
[2, 3, 4]

>>>
>>>
[1'
>>>
[3,

arr = [1, 2, 3, 4' 5]


de1 arr[4]; arr #
2, 3, 4]
de1 arr[:2]; arr #
4]

remove

de1:

(<>) - , .

va1ueError.

. :

>>> arr = [1, 2, 3, 1, 1]


>>> arr.remove(1)
#
>>> arr

[2, 3, 1' 1]

>>> arr.remove(5)
#
Traceback (most recent 11 1ast):
Fi1e "<pyshe11#3>", 1ine 1, in <modu1e>
arr. remove (5)
#
Va1ueError: 1ist.remove(x): not in 1ist
,
, .
, (, ,

).

>>> arr = [1, 2, 3, 1, 1, 2, 2, 3, 3]


>>> s = set (arr)
#
>>> s

{ 1, 2, 3}

>>> arr = 1ist(s)


>>> arr
[1, 2, 3]

# n
# n

TypeError. :

8.

8.8.

147

in.
Fa1se.

True,

>>> 2 in [1, 2, 3, 4, 5], 6 in [1, 2, 3, 4, 5] #


(True, Fa1se)
,

in

. , ~

index () .

ind(<>[,

index ()

<>[,

<>]])

, .

Va1ueError.

, . :

> arr = [1, 2, l, 2, 1]


>>> arr.index(1), arr.index(2)
(0, 1)

>>> arr.index(1, 1), arr.index(1, 3, 5)


(2,

4)

>>> arr.index(3)
Traceback (rnost recent 11 1ast) :
Fi1e "<pyshell#16>", 1ine 1, in <rnodu1e>
arr.index(3)
Va1ueError: 3 is not in 1ist

count (<>). , . :
> arr = [1, 2, 1, 2, 1]
>>> arr.count(1), arr.count(2)
(3, 2)

> arr. count ( 3)

rnax ()

rnin ()

. :

> arr = [1, 2, 3, 4, 5]


>>> rnax(arr), rnin(arr)
.(5, 1)
n(<>)

True,

, rue.

Fa1se.

>>> any([O, None]), any([O, None, 1]), any([])


(Fa1se, True, Fa1se)

all

(<>)

True,
True

148

1.

Python 3

> 11 ( [0, None]), all ( [0, None, 1]), all ( []), all ( C'str", 10])
(Fa1se, Fa1se, True, True)

8.9.

reverse ()

t!. :

>>> arr = [1, 2, 3, 4, 5]


>>> arr.reverse()
>>> arr

[5, 4, 3, 2, 1]
,

reversed (<>). ,
1ist ()

>>> arr. = [1, 2, 3, 4, 5, , 7, 8, 9, 10]


>>> reversed(arr)
<1ist_reverseiterator object at OxOOFD5150>
>>> 1ist(reversed(arr))
#n 1ist()
[10, 9, 8, 7, , 5, 4, 3, 2, 1]
>>> for i in reversed(arr): print(i, end=" ") # n
10 9 8 7 5 4 3 2 1
>>> [i for i in reversed(arr)] #n
[10, 9, 8, 7, , 5, 4, 3, 2, 1]

shuff1e (<n> [,

<

1. > J)

random

""

. .

random ().

.,

>>>
>>>
>>>
>>>

import random
# random
arr = [1, 2, 3, 4' 5, , 7, 8, 9, 10]
random.shuff1e(arr)
# n ~
arr
[2, 7, 10, 4' , 8, 9, 3, 1, 5]

8.1 .

random:
choice (<>) -

(, , ):

>>> import random # random


>>> random.choice(["s", "t", "r"]) #n
s'

8.

149

+ samp1e (<>,

<

>) -

. ,

.
, . :

>>> arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


>>> random.sample(arr, 2)
[7' 10]
# n
>>> arr
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

8.11.

sort (). :
sort([key=None] [, reverse=fa1se])
.
. :

>
>
>>>
[1,

arr = [2, 7, 10, 4, 6, 8, 9, 3, 1, 5]


arr. sort ()
arr
2, 3, 4, 5, 6, 7, 8, 9, 10]

, reverse

True:
>>> arr = [2, 7, 10, 4, 6, 8, 9, 3, 1, 5]
>>> arr.sort(reverse=True)
>>> arr
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

, (

8.8).

~<J1r 8.$;.~:~...i~

;.: ................... :....... :.::'.'.: ... :::............ :.. :.:: ....... :.:..;;::... :.:: ... :, .. ::::::::::.:.':.: .. : ... :;:.: ..

arr = [ "1", "",


arr.sort ()
for i in arr:
pr1nt(i, end=" ")

m:

"2"]

1. ,
key (

arr = ["1", "",


arr.sort(key=str.1ower)
fo1 i in arr:
print(i, end=" ")

m:

8.9).

"2"]

lower()

150

/.

Python 3

sort ( J .

,
. sorted ().
:

key=None] [, reverse=False])

srtd(<>[,

, .

sort ().

sorted() 8.10.

>>> arr = [2, 7, 10, 4, , , 9, 3, 1, 5]


>>> sorted(arr)
#
[1, 2, 3, 4, 5, , 7, , 9, 10]
>>> sorted(arr, reverse=True) #
[10, 9, , 7, , 5, 4, 3, 2, 1]
>>> arr = ["1", "", "2"]
>>> sorted(arr, key=str.1ower)
['1',

8.12.

'2',

'']

, , range ().
, . ,

list (). range () :

range ( [<>, ] <> [,

<>]

. <> ,
. .

, .
<> ,

1.

10:

>>> list(range(11))
[0, 1, 2, 3, 4, 5,

7,

9, 10]

, 1 15:

>>> list(range(1, 1))


[1, 2, 3, 4, 5, , 7,

9, 10, 11, 12, 13, 14, 15]

>>> list(range(15, , -1))


[15, 14, 13, 12, 11, 10, 9,

7,

5, 4, 3, 2, 1]

(
), sarnple (<>,
>)

>>> import random


>>> arr = [1, 2, 3, 4, 5,

random. :

7,

9, 10]

<

8.

151

>>> randorn.samp1e(arr, 3)
[1, 9, 5]

>>> randorn.samp1e(range(300), 5)
[259, 294, 142, 292, 245]

8.1 3.

join ().

. :
<>

= <>.jin(<>)

>>> arr = [ "word1", "word2", "word3"]


>>> " - ".join(arr)
'word1 - word2 - word3'
, ,

TypeError:

>>> arr = ["word1", "word2", "word3", 2]


> " - ". join (arr)
Traceback (rnost recent 11 1ast):
File "<pyshe11#69>", 1ine 1, in <rnodu1e>
"~ ".join(arr)
TypeError: sequence itern 3: expected str instance, int found
-,

str ():

>>> arr =. ["word1", "word2", "word3", 2]


'> "- ".join( ( str(i) for i in arr) )
'word1- word2- word3- 2'
,

str ()

>>> arr = ["word1", "word2", "word3", 2]


> str (arr)
" [ 'word1', 'word2', 'word3', 2]"

8.14.

, , .

, 1-

. , - , " ".

tup1e ( [<>]).

. ,
. :

> tup1e ()
()

152
#
>>> tup1e ( "String")
('S', 't', 'r', 'i', 'n', 'g')
>>> tup1e([1, 2, 3, 4, 5]) #

/.

Python 3

(1, 2, 3, 4, 5)

( ):
()
>>> t1
# n .
>>> t2
(5,)
#
(1, "str", (3, 4)) #
>>> t3
>>> t4
1, "str", (3, 4)
# .
>>> t1, t2, t3, t4
((), (5,), (1, 'str', (3, 4)), (1, 'str', (3, 4)))

.
, . ,
. ,
. :

>>> t = (5); type(t)


<c1ass 'int'>
>>> t = ("str"); type(t)
<c1ass 'str'>

# ,

, . ,

Python

, , .
. ,

( ) , 1. ,
, ,
(+), (*), (

in). :

'

>>> t = (1, 2, 3, 4, 5, , 7, 8, 9)
# n
>>> t [0]
1
>>> t [: :-1]
# n
(9, 8, 7, , 5, 4, 3, 2, 1)
>>> t[2:5]
#
(3, 4, 5)
>>> 8 in t, in t
#
(True, Fa1se)
>>> (1, 2, 3) * 3
#
(1, 2, 3, 1, 2, 3, 1, 2,, 3)
>>> (1, 2, 3) + (4, 5, ) #
(1, 2, 3, 4, 5, )
. , , :

>>> t = (1, 2, 3)
>>> t[OJ

#
#

no

no

>>> t

[]

50

153

Traceback (most recent 11 1ast) :


Fi1e "<pyshe11#95>", 1ine 1, in <modu1e>
t[O] =50
# no !
TypeError: 'tup1e' object does not support item assignment
n

> t = (1, 2, 3)
> 1en(t)

#
#

1en ():

Python 2.6,

n :

t index (<> [,

<>

Va1ueError.

[,

<>]]

)-

n , n n

. :

>>> t = (1, 2, 1, 2, 1)
>>> t.index(1), t.index(2)
(0, 1)

>>> t.index(l, 1), t.index(l, 3, 5)


(2,

4)

> t.index(3)

Va1ueError: tup1e.index(x):

t count (<>) -

not in tup1e

, . :

>>> t = (1, 2, 1, 2, 1)
>>> t.count(l), t.count(2)
(3, 2)

> t.count (3)

. n n ,
, n n
. n n.

8.15.

itertoo1s

itertools

, .n n

n, n .
, n . n

, n n :

import itertoo1s

8.15.1.

n n :

t count ( [start=O] [, step=1])-

. n

start,

- n

step.

154

/.

Python 3

>>> import itertools


>>> for i in itertools.count():
if i > 10: break
print(i, end=" ")
1 2 3 4 5 6 7 8 9 10
>>> list(zip(itertools.count(),

[10,

''),

''),

(1,

(2,

''),

""))
''),

(3,

'')]

(4,

>>> 1ist(zip(ltertools.count(start=2, step=2),


[(2, ''), (4, ''), (6, ''), (8, ''), (10,

cycle (<>) -

""))
'')]

. , n
. . :

>>> n = 1
>>> for i in itertools.cyc1e("a"):
if n > 10: break
print(i, end=" ")

+= 1

> list(zip(itertools.cycle([O, 1]), ""))


[(0, ''), (1, ''), (0, ''), (1, ''), (0, '')]

repeat

(<>

< >])

[,

, :

>>> 1ist(itercools.repeat(1, 10))


[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
>>> list(zip(itertoo1s.repeat(5),
[(5, ''), (5, ''), (5, ''), (5,

8.15.2.

""))
''),

(5,

'')]

n :

cominations

() -

. :
mintins(<>,

< >)

>>> import itertoo1s


>>> list(itertools.cominations('a', 2))
[('',

''),

('',

'')]

('',

''),

>>> ["".join(i) for i in


[ ' ' , ' ' ' ' ' , ' ' '

('',

''),

{'',

''),

('',

itertools.cominations('a',

' '

'

''

''),

2)]

>>>

2))

list(itertools.cominations('a',

[('',

''),

('',

'')]

>>>

155

('',

''),

('',

''),

('',

list(itertools.cominations('a',

[('',

'',

''),

('',

'',

'')]

('',

'',

''),

('',

''),

3))

('',

+ cominations_with:_replacernent () -

''),

'',

''),

. :
cominations_with_replacernent(<oceoaeoc>,
<

>)

>>>

list(itertools.cominations_with_replacernent('a',

2))

[('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

'')]

>>> list(itertools.cominations_with_replacernent('a', 2))


[ ('', ''), ('', ''), (!', ''), ('', ''), ('', ''),
('',

''),

('',

perrnutations () -

''),

('',

''),

('',

''),

('',

'')]

, .

. ,

. . :
rmuttins(<>[,

< >])

>>>

2))

list(itertools.perrnutations('a',

[('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

'')]

>>> ["".join(i) for i in

itertools.perrnutations('a')]

['',

'',

'',

'',

'',

'',

'',

'',

'',

'',

'',

'',

.'',

'',

'',

'',

'',

'',

'',

'',

'',

'',

'',

'']

product () -

. :
rdut(<l>[,

... ,

<N>]

[,

repeat=l])
:

>>> frorn itertools irnport product


>>> list(product('a', repeat=2))
[ ('', '')' (''' ''), ('', ''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

('',

''),

{'',

'')'

('',

''),

('',

''),

('',

''),

('',

''),

('',

'')]

>>> ["".join(i) for i in product ( ' ' ,


[ '', '', '', '']

'',

repeat=l)]

156
>>> ["".join(i) for i

inproduct('a',

'',

'',

'',

'',

'',

:',

'',

'',

'',

'',

'',

'',

'',

8.15.3.

''

Python 3

repeat=2)]

'',

['',

''

/.

filterfa1se (<u>, <>)-


( ), ,
, Fa1se. :

>>> irnport itertoo1s


>>> def func(x): return
>>>
[0,
>>>
[ 4'

> 3

1ist(itertoo1s.filterfa1se(func, [4, 5, ,
2, 3]
1ist(filter(func, [4, 5, , , 7, 2, 3]))
5, , 7]

7, 2, 3]))

None,

Fa1se.

True, ,
. :

>>> 1ist(itertoo1s.filterfa1se(None, [0, 5,


[0,

>>> 1ist(fi1ter(None, [0, 5,


[5, , 7' 3]

7,

3]))

dropwhi1e ( <u>,

7,

3]))

<>)

( ), , ,
,

>>> def func

():

return

Fa1se. :

> 3

>>> 1ist(itertoo1s.dropwhi1e(func, [4, 5,


[0, 7, 2, 3]
>>> 1ist(itertoo1s.dropwhi1e(func, [4, 5,

7, 2, 3]))

7, 8]))

[]

>>> 1ist(itertoo1s.dropwhi1e(func,
[1, 2, 4' 5, , 7, 8]

takewhi1e ( <u>,

[1, 2, 4' 5,

<>) -

7, 8]))

( ), ,

, , Fa1se. :

>>> def func


>>>
[ 4'
>>>
[ 4'
>>>
[]

()

: return

> 3

1ist(itertoo1s.takewhi1e(func, [4, 5,

5,

7, 2, 3]))

1ist(itertoo1s.takewhi1e(func, [4, 5, , 7, 8]))


5, , 7, 8]
1ist(itertoo1s.takewhi1e(func, [1, 2, 4, 5, , 7, 8]))

157

8.

compress () -

. , (
) . ,
. :
mrss(<

>,

<

>)

>>>

1ist(itertoo1s.compress('ae',

['',

>>>

'',

1isL:(itertoo1s.compress('ae',

['',

8.15.4.

[1,

1, 1]))

'']

[True, Fa1se, True]))

'']

, , itertoo1s
:

starmap(<yl..I.>,

<>)-

. ,
.
. ,
, . :

>>> import itertoo1s .


>>> def fuc1(x, ): return

> 1ist (itertoo1s.starmap(func1, [ (1, 2),


[3, 9, 13]
>>> def func2(x, , z): return ++ z
> 1ist (itertoo1s.starmap(func2,
[6, 15]

zip_1ongest () -

(4, 5),

[ (1, 2, 3),

(6, 7)]))

(4, 5, 6)]))

, .
,

fillva1ue. :

zi_1ngst(<1>[,

... ,

<N>]

[, fi11va1ue=None])
:

> 1ist (itertoo1s. zip_1ongest ( [1, 2, 3],


[(1, 41, (2, 5), (3, 6)]
> list (itertoo1s.zip_1ongest ( [1, 2, 3],
[ (1, 4), (2, None), (3, None)]
> 1ist(itertoo1s,zip_1ongest([1, 2, 3],
[(1, 4),

(2, 0),

(3, 0)]

> 1ist(zip([1, 2, 3],


[ ( 1, 4)]

[4]))

[4, 5, 6]))
[4]))
[4], fillva1ue=0))

158

accumu1ate

(<>)

/. Python 3

. . :

>>> 1ist(itertoo1s.accumu1ate([1, 2, 3, 4, 5, 6]))


[1, 3, 6, 10, 15, 21]
>>> # [0+1, 1+2, 3+3, 6+4, 10+5, 15+6]

chain () -

, . . :
hin(<1>[,

... ,

<N>])

>>>
>>>
[1,
>>>

arr1, arr2, arr3 = [1, 2, 3], [4, 5], [, 7, , 9]


1ist(itertoo1s.chaln(arr1, arr2, arr3))
2, 3, 4, 5, , 7, , 9]
1ist ( itertoo1s. chain ( "", "defg", "hij") )
['',
'',
'',
'd', '', 'f', 'g', 'h', 'i', 'j']
>>> 1ist ( i tertoo1s. chain ( "", [ "defg", "hij "J ) )
['',

'',

'',

'defg',

chain. from_ i terae

'hij'J

(<>)

chain (),

.
. :

>>>

tee

"defg", "hij"]))
'g', 'h', 'i', 'j']

1ist(itertoo1s.chain.from_iterale(["abc",

['',

'',

'',

'd',

'',

(<>

[,

'f',

<>]

)-

. ,
. :

>>> arr = [1, 2, 3]


>>> itertoo1s.tee(arr)
(<itertoo1s.tee object at Ox00rDB760>,
<itertoo1s.tee object at Ox00rDB73B>)
>>> itertoo1s.tee(arr, 3)
(<itertoo1s.tee object at Ox00rDB710>,
<itertoo1s.tee object at Ox00rDB7DB>,
<itertoo1s.tee obJect at Ox00rDB7B0>)

- , n

no

no

. , n ,

. r n n

f1 . ,
n

n.

n ,

, n n .

, n. n ,
n n, n ,
, n ., n. n,
n . , n

9.1.

no

, .

n:

dict

(). :

dit(<1>=<1>[,

... ,

<N>=<N>])

dit(<>)

dit(<
dit(<

(,
[,

)>)
]>)

n , n . :

>>> d

dict(); d

{}

>>> d = dict(a=1, =2); d


{'': l,
'': 2}
>>> d = dict ( {"": 1, "!': 2}); d
#
{'': 1,
'': 2)
>>> d = dict([("a", 1), ("", 2)]); d #
{'': 1, '': 2)
>>> d = dict ( [ ["", 1], ["", 2]]); d #
{'': 1,
'': 2)

160

/. Python 3

zip ( J:
["", ""]
# n
# n
[1; 2]
>>> list(zip(k, v))
#
[ ('', 1), ( '', 2) J
>>> d = dict(zip(k, v)); d #

>>> k

> v

('':

1,

'':

2}

.
. ,

"/" . :

{ }; d

>>> d

{}

>>> d

{'':

1,

"":
'':

1,

"":

2 }; d

2}

d = {}
d["a"]
1
d["b"]
2
d
{'': 1,
'': 2}

#
#
#

>>>
>>>
>>>
>>>

"")

"")

dict. fromkeys (<> [, <>] ) .

, .
, None. :

>>> d = dict.fromkeys(["a", "", ""])


>>> d
{ ' ' : None, '' : None, '' : None}
>>> d = dict.fromkeys(["a", "", ""], 0)
>>> d
{'':

>>> d
>>> d

{'':

'':

'':

0}

dict.fromkeys(("a",
'':

'':

# ;

"",

""),

)#

, .
.

, .
:

>>> dl = d2
{ "": 1, "": 2 } #
>>> d2["b"] = 10
>>> dl, d2
#
({'': 1,
'': 10}, {'': 1,
'': 10})

!!

, d2
dl. ,
, . ,
:

9.

>>> d1, d2

> d2["b"]
> d1, d2
1,

({'':

{
=

'':

"":

1,

"":

161
2 }, {

"":

1,

"":

2 }

10
2},

{'':

1,

'':

10})

dict 1) (

. 9:1. .

..

9.1 ).

. . . . . . . . . . . . . . . . . . . . . . . . :

l...:_....~-~~~-~~
<:~;~-~-~~ ~i~~~;~;;;;;'~;;~~~ ;;i;J~~ ~Q~~~; ~~~~~~~~~<>
...........................................:,. ............... """;;:................ ;,,,,,,,,,;,,;. ;;,,, ...,;,,;,,,,; .................... :.... ; ............................. ................................................. ...........
,;

;;;,,,

>>> d1 = { "": 1, "": 2 } #


>>> d2 = dict(d1)
#
>>> d1 is d2 # ,
Fa1se
> d2["b"] = 10
>>> d1, d2
# d2
({'': 1,
'': 2},
{'': 1,
'': 10})
, ~ 1)

9.2).

[ 9.2. . ntiQfin t~~osap~t ii() t.

k.. :;, .......;...'................-........ ,.,;;, ..-..............:.:: ...;;.:=~;;,,,;:........ ;,, .. ~.;'l~:];';;[.j~jl~::;;~[~;;;,:.;;,;::;, ....'.=.:;....:.~.:: ..=.;;;~=.:;;;:.:~;;;:;=,;.,; .. :; ..~~; ... :;:.: ..:::~ ..'.';~;.::: ....'. ;:;.~ ;..~.;:.~: :. ;;,, ................. ""''""'"''"'''"''

>>> d1 = ( "": 1, "": 2 } #


>>> d2 = d1.copy()
#
>>> d1 is d2 # ,
Fa1se
> d2["b"] = 10
>>> d1, d2
# d2
({'': 1,
'': 2},
{'': 1,
'': 10})
, deepcopy
(

1)

9.3).

ii'~t;~~~~-:;c~;~~~;~~-~~~:~J~~~-~J-~r;

. . . . . . . .". .". . . . . . . . . . . . .
~

e ................... , ........ , ............................................................

:.. '.:: ..... '' ..... ' .. """." ... "... "....:"." .., ......... ;;,; : ;, ;.~ ;.. "...=;; i. =,;. .. "" .. :;.. ;.. "."""' .. ,;;.~ .. :; :..... "'" ...... ". ;, ;~. .;,.;, ................~ ;,; ;;,.: .,',:: ;;, ;,.,;," "' ......... '.... ;.......... ""' .... ;."........... "' ....... "'"".' ........... ;

d1 = { '"": 1, "": [20, 30, 40] }


#
d2 = dict(d1)
d2 [""] [0] = "test"
d1, d2
# r! ! !
({'': 1, '':
['test', 30, 40]}, {'': 1, '': ['test', 30, 40]})
> 1mport
>>> d3 = copy.deepcopy(d1) #
> d3["b"] [1] = 800
>>> d1, d3
# d3
({'': 1,
'':
['test', 30, 40]}, {'': 1, '': ['test', 800, 40]})

>>>
>>>
>>>
>>>

9.2.

. , ,
.

1349

162

/.

Python 3

>>>d= { 1: "int", "": "str",


> d[1], d["a"], d[ (1, 2)]
( 'int' , 'str' , 'tup1e' )

(1, 2): "tup1e")

, , ,

KeyError:

>>> d = { "": 1, "":


>>> d["c"]
Traceback (most recent
File "<pyshell#49>",
d [""]
KeyError: ''

2 }
#
11 last) :
line l, in <module>
#

in. ,

True, - Fa.,J..se. :

>>> d = { "": 1,
>>> "" in d
True
>>> "" in d
False

"":

get (<> [, < no >])

. ,
, . ,

None , n. :

>>> d = { "": 1, "": 2 }


>>> d.get("a"), d.get("c"), d.get("c", 800)
(1, None, 800)
, setdefault(<rno>[,

<

>]). , ,
. , , ,
n. ,

None. :
>>> d = { "": 1, "": 2 }
>>> d.setdefault("a"), d.setdefault("c"), d.setdefault("d", 0)
(1, None, 0)
>>> d
{ ' ' : 1, '' : None, '' : 2, 'd' : }
,
. ,
:

>>>d= {"": 1, "": 2}


>>> d["a"]
800
>>> d["c"] = "string~
>>> d
{'': 800,
'': 'string',

#
#
'':

2}

9.

163

>>> d = {
>>> len(d)
2

"":

1,

"":

2 )

>>> d = { "": l,
>>> del d["b"]; d

"":

len i):

del:

2 )

""

{'':

l)

9.3.

for,

. .

keys (), .

.
,

. (

9.4).

'""'"""''(''""".''''"'""''"''''"''"'''""'""""""'""'"""'"''""'""'~'""~'"'""".'""".'.~'""""'"""'""".''"""""."!'<'""('"'~~".'.:'"'''".'('.'!'"".'(~.'!"'"""'"."!"''"''""""'""'''"

.........................~. ......... ,.

.:.~.~~~~~..~.:~.~~.~~~.~;;~~.~~.~.~~?.~.;~,?.~.~~'-- ' .........;. .,......; ...........,.....;......................,.................................................!


{"": 1, ": 2,
"z": 3}
for key in d.keys():
# keys()
print("({O) => {l))".format(key, d[key]), end=" ")
# : ( => 2) ( ~> l) (z => 3)
print ()
#
#
for key in d:
print (" ( {0} => {l})".format(key, d[key]), end=" ")
# : ( => :') ( => l) ( z => 3)

d =

. ,
.

{"":

1,

"":

'2.,

sort ().

"z": 3}

k = list(d.keys() 1
#
k. sort ( )
#
for key in k:
print("({O) => {l})".format(key, d[key]), end=" ")
# : ( => l) ( => 2) (z => 3)

sort ()

sorted ( 1.

d =

{"":

1,

"":

2,

"z": 3}

for key 1n sorted(d.keys()):


print("({O} => {l))".format{key, d[key]), end=" ")
# : { => l) (=> 2) {z => 3)
,
,

keys ():

sorted ( 1

164
d =

{"":

1,

/.

Python 3

2, "z": 3}

"":

for key in sorted(d):


print("({O) => {1))".format(key, d[key]), end=" ")
# : '( => 1) ( => 2) (z => 3)

9.4.

keys () -

dict_keys, .

, . :

>>> d1, d2 = { "": 1, "": 2 }, { "": 3, "": 4, "d": 5 )


>>> d1.keys(), d2.keys() # dict~keys
(dict_keys(['a', '']), dict_keys(['a', '', 'd']))
>>> 1ist(d1.keys()), 1ist(d2.keys()) #
( ['', ''], ['', 'r::', 'd'.J)
>>> for k in d1. keys () : print ( k, end=" ")

>>> d1.keys ()

d2. keys ()
'd'}
> d1.keys() - d2. keys ()
{ ''}
> d2.keys() - d1. keys ()
{'',
'd'}
> d1.keys() & d2. keys ()
{'',

{''

'',

11

> d1. keys ()


{'',

'',

'',

va1ues () -

d2. keys ()

'd' J

dict_va1ues, .

. :

>>>d= {"": 1, "": 2 J


>>> d. va1ues ()
dict_va1ues([1, 2])
>>> 1ist(d.va1ues())

dict va1ues

[1, 2]

>>> [ v for v in d.va1ues() ]


[1, 2]

items ()

dict_items,

. . :

>>> d = { "": 1, "": 2 J


>>> d.items()
#
dict_items([('a', 1), ( '', 2)])
>>> 1ist(d.items())
#
[ ('', 1), ( '', 2)]

<>

dict_items

in <>- l .
True, - Fa1se.

9.

165

>>> d = {
>>>

1,

"":

"":

2 }

""

in d

""

in d

True
>>>

Fa1se

t get (<> [,

< >]) - ,

, . ,

None

, . :

>>>d= {"": 1, "": 2}


>>> d.get("a"), d.get("c"), d.get("c", 800)
(1, None, 800)

t setdefau1 t

(<>

[,

< >]

}-

, . ,
, .
,

None.

>>> d = { "": 1, "": 2 }


>>> d.setdefault("a"),d.setdefau1t("c"),d.setdefau1t("d", 0)
(1, None, 0)
>d
{ '' : 1, '' : None, '' : 2, 'd' : }

(<>

[,

<

>])

. ,
. ,

KeyError.

>>> d = { "": 1, "": 2, "": 3 }


>>> d.pop("a"), d.pop("n", 0)
(1, 0)

>>> d.pop("n") #
Traceback (most recent call 1astJ :
Fi1e "<pyshell#40>", 1ine 1, in <modu1e>
d.pop("n") #
KeyError: 'n'
>>> d
{'':

3,

'':

2}

t popitem()-

>>> d = { "": 1,
>>> d.popitem() #
('',

"":

KeyError.

2 }

1)

>>> d.popitem() #

( '', 2)

>>> d.popitem() # .
Traceback (most recent 11 1ast}:
Fi1e "<pyshell#45>", 1ine 1, in <moduie>
d.popitem() # .
KeyError: 'popitem(): dictionary is empty'

166

/.

Python 3

c1ear () - .
. :

>>> d = { "": 1,
> d. c1ear ()
>>> d

2 }

"":

#
#

{)

update () -

. :
udt(<1>=<1>[,

... ,

<N>=<N>])

udt(<>)

update(<Cnco >)
update(<Cnco

>)

,
. :

>>> d = { "": 1, "": 2 }


>>> d.update(c=, d=4)
>>> d
{'':

1,

'':

3,

'':

2,

'd': 4}

>>> d.update({"c": 10, "d": 20))


#
>>> d # n
{'': 1,
'': 10,
'': 2,
'd': 20}
>>> d.update([("d", 80), ("", )])
# n
>>> d
{'': 1; '': 10, '': 2,
'': ,
'd': 801
>>> d.update([["a", "str"], ["i", "t"]]) #n
>>> d
{'': 'str',
'': 10, '': 2,
'': , 'd': , 'i': 't'}

() - :

>>> d1 = { "": 1, "": [10, 20] }


>>> d2 = d1.copy() # n n
>>> d1 is d2
#
Fa1se
>>> d2["a"] = 800 #
>>> d1, d2
# d2
({'': 1, '': [10, 20]), {'': 800, '': [10, 20]})
>>> d2 [""] [0] = "new" # n
>>> d1, d2
# d1, d2t!!
({'': 1, '': ['new', 20]}, {'': 800,
'': ['new', 20]})
,

deepcopy ()

9.5.

Python 3

, ! :

9.

167

, ;

for ,

. , , , ,
,- .

>>> keys =

""]
#
[1, 2]
#
> {k: v for {k, v) in zip(keys, values)}
["",

>>> values =
{'':

1,

>>> {k:
{'':

'':

2}

for k in keys}
'': 0}

. ,

for () i f .

, , :

>>> d = { "": 1, "": 2, "": 3, "d": 4


>>> {k: v for (k, v) in d~items() if v% 2 == 0}
{ '': 2, 'd': 4}

9.6.

- ,
, , .

, , , .

set ():
>>> s = set ()
>>> s
set ()

set 1) :

>>> set("string")

#
{ 'g', 'i f, 'n'' 's', 'r', 't 1}
>>> set ( [1; 2, 3, 4, 5])
#
{1, 2, 3, 4, 5)
>>> set ( (1, 2, 3, 4, 5))
#
{1, 2, 3, 4, 5}
>>> set ( [1, 2, 3, 1, 2, 3]) #
{1, 2, 3}

Python 3 , ..

, ,
. ,
:

>>> {1, 2, 3, 1, 2, 3}

{1, 2, 3}
>>>

{), set()

set 1).

168
> type

_#

()

<cla55 'dict'>
> type ()

1.

Python 3

!!!

<cla55 '5et'>
n for:

>>> for i in 5et([1, 2, 3]): print(i, end=" ")

1 2 3
n len ():

> len(5et([1, 2, 3]))


3
n
:

1 union () - :
>>> 5 = {1, 2, 3}
> 5.union(5et([4, 5, 6])), 51 5et([4, 5, 6])

({1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6})


, n :

> 5et([1, 2, 3])

1 5et([1, 2, 3])

{1, 2, 3}

1= . update () - :

>>> 5 = {1, 2, 3}
>>> 5.update(5et([4, 5, 6]))
>>> 5
{1, 2, 3, 4, 5, 6}
>51= 5et([7, 8, 9])
>>> 5
{1, 2, 3, 4, 5,

+ - difference ()

7, 8, 9}

- :

> 5et([1, 2, 3])- 5et([1, 2, 4])


{3}

>>> {1, 2, 3}.difference(5et([1, 2, 4]))


{3}

-= . difference _ upciate () - ,
, :

>>> 5 = {1, 2, 3}
>>> 5.difference_update(5et([1, 2, 4]))
>>> 5
{3}

>5>>> 5
5et ()

5et([3, 4, 5])

&

9.

intersection () -

169

. ,

> set ( [ 1 , 2 , 3] )

&

set ( [ 1 , 2, 4 ] )

{1' ~}
>>> s = {1, 2, 3}
>>> s.intersection(set([1, 2, 4]))
{1, 2}

&= .

intersection_update ()

- ,

, :

>>> s = {1, 2, 3}
>>> s.intersection_update(set([J, 2, 4]))
>>> s
{1' 2}
>>> s &= {1,
>>> s

7}

{ 1)

symmetric_ difference () -

>

s
>>> s

{1, 2, 3)

set([1, 2, 4]), s.symmetric_difference(set([1, 2, 4]))

( { 3, 4}'

>>> s
(set (),
>>> s
( {1, 2,

{ 3, 4})

set ( [1, 2, 3])' s.symmetric_difference(set([1, 2, 3]))


set ())
set ( [ 4, 5, ])' s .symmetric_difference (set ( [ 4, 5, ]))
3, 4' 5, }' {1, 2, 3, 4, 5, })

a.symmetric_difference_update(b)-

, :

>>> s = {1, 2, 3}
>>> s.symmetric_difference_update(set([1, 2, 4]))
>>> s
{3, 4}

>>> S
>>> s

{ 4' 5,

{3, 5,

n :

in-

>>> s = {1, 2, 3, 4, 5}
>>> 1 in s, 12 in s, 12 not in s
(True, Fa1se, True)

= = - :

> set ( [1, 2, 3]) == set ( [1, 2, 3])


True
> {1, 2, 3} == {3, 2, 1}
True

170

Python 3

set ( [ 1 , 2 , 3, 4 J )

> set ( [1, 2, 3])


Fa1se

1.

a.issuset ()- ,

<=

>>> s = {1, 2, 3}
>>> s <= set([1, 21), s <= set([1, 2, 3, 4])
(Fa1se, True)
>>> s.issuset(set([1, 2])), s.issuset({1, 2, 3, 4})
(Fa1se, True)

<

- , .

>>> s = {1, 2, 3}
>>> s < set([1, 2, 3]), s < set([1, 2, 3, 4])
(Fa1se, True)

>= . issuperset () -

>>> s = {1, 2, 3}
>>> s >= set([1, 2]), s >= set([1, 2, 3, 4])
(True, Fa1se)
>>> s.issuperset(set([1, 2])), s.issuperset({1, 2, 3, 4})
(True, Fa1se)

> - , .

>>> s = {1, 2, 3}
> s > set([1, 2]), s > set([1, 2, 3])
(True, Fa1se)

isdisjoint () - True,

( , ~ ):

>>> s = {1! 2, 3}
>>> s.isdisjoint(set([4, 5, 6]))
True
>>> s.isdisjoint(set([4, 1, 6]))
False
l>! :

( J -

. ,

, . :

>>> s
>>>
True

s; s is

>>>=

s.copy()

>>>

{1, 2, 3}

{1, 2, 3}

>>> s is
Fa1se

9.

t add (<>) -

171

<> :

>>> s = { 1, 2, 3)
> s.add(4); s
{1, 2, 3, 4)

t remove (<>)

- <> . ,

>>> s = {1, 2, 3)
>>> s.remove(3); s

KeyError:
#

{1, 2)

>>> s.remove(5)
#
Traceback (most recent call 1ast):
Fi1e "<pyshe11#71>", 1ine 1, in <modu1e>
s.remove(5)
#
KeyError: 5

disrd(<>)- <> , :

>>>
>>>
{1,
>>>
{1,

s = {1, 2, 3)
s.discard(3); s
2)
s.discard(5); s
2)

() - .
,

KeyError:

>>> s = {1, 2)
>>> s.pop(), s
(1, {2))
>>> s.pop(), s
(2, set())
>>> s.pop() # ,
Traceback (most recent 11 1ast):
Fi1e "<pyshell#81>", line 1, in <modu1e>
s.pop() # ,
KeyError: ' from an empty set'

t c1ear ()

- :

>>> s = {1, 2, 3)
>>> s.c1ear(); s
set ()

Python

frozenset. set,
frozenset .

frozenset ():

>>> f = frozenset()
> f
frozenset ()

frozenset ()

172
>>> frozenset("string")
frozenset ( { 1 g 1 ' 1 i 1 ' 1 n 1 ' 1 s 1 '
>>> frozenset ( [1, 2, 3, 4, 4])
frozenset({1, 2, 3, 4})
>>> frozenset( (1, 2, 3, 4, 4))
frozenset((1, 2, 3, 4})

1 '

/.

Python 3

't 1 } 1

frozenset , ,
difference ( 1, isdisjoint (), intersection (), issuset ( 1,
issuperset (), symrnetric_ difference () union ().

: (),

9. 7.

Pyth~n

. ,

, .
f, . :

>>> { for
{1, 2, 3}

in [1, 2, 1, 2, 1, 2, 3]}

. ,

for () if .
, ,
:

>>>
{2}

for

in [1, 2, 1, 2, 1, 2, 3] if

%2

==

0}

10

Python

time- ,
;

datetime-

, ,
.;

ca1endar- L-;
timeit-
.

10.1. '

time () -

>>> import time


>>> time.time()
1303520699.093

grntime ( [<

#
#

1 1970

.):

time

>])

(UTC).

time:

struct_time,

, .

, ,

, . :

>>> time.grntime(O)
# n
time.struct time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=O,
tm_min=O, tm_sec=O, tm_wday=3, tm_yday=1, tm_isdst=O)
>>> time.grntime()
#
time. struct time (tm_year=2011, tm_mon=4, tm_mday=23, tm_hour=1,
tm_min=B, tm_sec=9, tm_wday=S, tm_yday=113, tm_isdst=O)
>>> time.grntime(1283307823.0)
# 01-09-2010
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=1, tm_hour=2,
tm_min=23, tm_sec=43, tm_wday=2, tm_yday=244, tm_isdst=O)

174

/.

Python 3

,
:

>>> d = time.gmtime()
>>> d.tm_year, d(O]
(2011, 2011)
>>> tup1e(d)
#
(2011, 4, 23, 1, 10, 24, 5, 113, 0)

1ocaltime ([< >])- struct_time,


. , .

, , - ,
. :

>>> time .11 time ()


# ~
time.struct time(tm year=2011, tm_mon=4, tm_mday=23, tm_hour=5,
tm_min=12, tm_sec=55, tm_wday=5, tm_yday=113, tm_isdst=1)
>>> time.1oca1time(1283307823.0) # 01-09-2010
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=1, tm_hour=,
tm_min=23, tm_sec=43, tm_wday=2, tm_yday=244, tm_isdst=1)

mktime(<Oe

struct_time>)-

, .

struct_time

. ,

overflowError. :

>>> d = time.1oca1time(130352099.0)
>>> time.mktime(d)
130352099.0

>>> tup1e(time.1oca1time(130352099.0))
(2011, 4, 23, 5, 4, 59, 5, 113, 1)
>>> time.mktime((2011, 4, 23, 5, 4, 59, 5, 113, 1))
.130352099.

>>> time.mktime((1940, , 31, 5, 23, 43, 5, 31, 0))


. .. . ...
Overf1owError: mktime argument out of range

struct_time, gmtime() 1ocaltime(),

+
+
+
+
+
+
+
+
+

tm_year -

tm_mon- 1 - ( 1 12);
tm_mday- 2 - ( 1 31);
tm_hour- 3 - ( 23);
tm_min- 4 - ( 59);
tm_sec- 5 - ( 59, 61);
tm_ wday- - ( ( ) ( ));
tm_yday- 7 - , ( 1 3);
tm_isdst- 8 - ( , 1 -1).

,
- (

10.1 ).

1.

# -*- coding: utf-8 -*import time #


d

"n",

"n",

rn =

"",

"",

"",

time

"",

"",

"',

"",

"~<:"

"",

"",

175

"",

"",

"n~",

"",

"",

"",

"", "~<:" ]
t = time.1oca1time() # ~<:
print ( ": \n%s %s %s %s %02d: %02d: %02d\n%02d. %02d. %02d" %
( d[t[]], t[2], m[t[1]], t[O], t[3], t[4], t[5],
t[2], t[1], t[O] ) )
input ()

:
:

24 2011
24.08.2011

10.2.

1~:07:29

time:

strftime(<Cpo~<:a

>[,

<~<:

struct_time>])-

. ,
.

struct_time

. . :

>>> import time


>>> time.strftime("%d.%m.%Y") #
'24.08.2011'
>>> time.strftime("%H:%M:%S") #
'05:26:51'
> time .strftime ("%d. %m. %", time .1ocaltime (1283307823. 0))
'01.09.2010'

strptime (<~<: > [,

<~<:

>]

)-

, .
,

struct_time.
va1ueError.

, "% % %d %: %: %S %". :

> time.strptime("Sat Apr 23 05:31:50 2011")


time.struct_time(tm_year=2011, tm_mon=4, tm_mday=23, tm_hour=S,
tm_min=31, tm_sec~50, tm_wday=5, tm_yday=113, tm_isdst=-1)
> time .strptime ( "23 .04. 2011", "%d. %m. %")
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=23, tm_hour=O,
tm_min=O, tm_sec=O, tm_wday=5, tm_yday=113, tm_isdst=-1)

176

/.

Python 3

>>> tirne.strptirne("23-04-2011", "%d.%rn.%Y")


...
Va1ueError: tirne data '23-04-2011' does not rnatch forrnat '%d.%rn.%Y'

asctirne ( [< struct_ tirne> J ) -

n .

n , n . n

struct_tirne ,

. :

#
>>> tirne.asctirne()
'Wed Aug 24 17:11:37 2011'
>>> time.asctirne(tirne.1oca1tirne(1283307823.0))
'Wed Sep 1 06:23:43 2010'

ctirne ( [ <JU1 >] ) -

asctirne (), n

n struct_tirne, , n n
. :

> tirne. ctime ()


'Wed Aug 24 17:12:30 2011'
>>> tirne.ctirne(1283307823.0)
'Wed Sep 1 06:23:43 2010'

n < > strftirne () strptirne () n


n :

+
+
+
+
+
+
+
+

%- ( "00" "99");
%- (n, "2011 ");

%rn- n ( "01" "12");


%- (n, "" );
%- (n, "");

%d- n ( "01" "31 ");


%j- ( "001" "366");
%u- ( "00" "53"). .
n ;

%W- ( "00" "53"). n.


n n ;

+
+

%w- (""- , "6"- );

%- (n, ""
n);

+
+
+
+
+
+
+

%- (n, "");
%- 24-~ ( "00" "23");

%I- 12- ( "01" "12");


%- ( "00" "59");

%S- ( "00" "59", "61");


%- ;
%- n ;

+
+

10.

177

%- ;

%- . :

>>> import locale


> loca1e.set1ocale(loca1e.LC_ALL, "Russian Russia.l251")
'Russian Russia.l251'
> print(time.strftime("%x"))
#
24.08.2011
>>> print(time.strftime("%X"))
#
5:46:20
> print (time. strftime ("%"))
#
24.08.2011 5:46:33

%Z- (, " ()");

%%-"%".

strft ime () (

10.2).

# -*- coding: utf-8 -*import time


import 1ocale
1oca1e.set1oca1e(loca1e.LC_ALL, "Russian Russia.l251")
s = ":\n% %d % % %H:%M:%S\n%d.%m.%Y"
print(tlme.strftime(s))
input ()
:
:

24 2011 17:15:00
24.08.2011

10.3.

""
s1eep ()

time

. :
s1(<

>)

.
,

time import time:

> import time


>>> time.s1eep(5)

#
#

"m"

time

from time import sleep:

>>> from time import s1eep


> s1eep(2.5)

#
#

time

"m"

178

10.4.

/.

Python 3

datetime.

datetime . ,

, ,
. ,
:

import datetime
:

timedelta- , .

date dat~time. ,
timede1ta;

+
+
+
+

date- ;
time- ;
datetime- ;
tzinfo- , .
datetime.

10.4.1.

timedelta

timedelta datetime n , ,
, , . :

timedelta ( [days] [, seconds] [, microseconds] [, milliseconds] [, minutes]


[, hours] [, weeks])
.
:

+
+
+

days- ( -999999999 <= days <= 999999999);


seconds- ( <= seconds < 3600*24);
microseconds- ( <= microseconds < 1000000).

milliseconds- ( 1000 11):


>>> import datetime
. >>> datetime.timede1ta(mi11iseconds=1)

datetime.timede1ta(O,

1000)

minutes- ( 60 ):
>>> datetime.timede1ta(minutes=1)
datetime.timede1ta(0, 60)

hours- ( 3600 ):
>>> datetime.timede1ta(hours=1)
datetime.timede1ta(O, 3600)

1.

179

weeks- ( 7 ):
>>> datetirne.tirnede1ta(weeks=1)
datetirne.tirnede1ta(7)

. :

>>> datetirne.tirnede1ta(O, , ,
datetirne.tirnede1ta(0, 3600)
>>> datetirne.tirnede1ta(hours=1)
datetirne.tirnede1ta(O, 3600)

1)

+
+
+

days

-;

seconds- ;
rnicroseconds -

> d = datetirne. tirnedelta(hours=1, days=2, rnilliseconds=1)


>>> d
datetirne.tirnede1ta(2, 3600, 1000)
>>> d.days, d.seconds, d.rnicroseconds
(2, 3600, 1000)
>>> repr(d), str(d)
('datetirne.tirnede1ta(2, 3600, 1000) ', '2 days, 1:00:V0.001000')
tota1_seconds () (

Python 3.2):

>>> d = datetirne.tirnede1ta(rninutes=1)
>>> d.tota1_seconds()
60.0
tirnedelta +, -, !,
1/, % *, + -,
abs (). :
'

> d1
datetirne.tirnede1ta(days=2)
>>> d2
datetirne.tirnede1ta(days=7)
>>> d1 + d2, d2 - d1
(datetirne.tirnede1ta(9), datetirne.tirnede1ta(5))
>>> d2 1 d1
3.5
>>> d1 1 2, d2 1 2.5
(datetirne.tirnede1ta(1), datetirne.tirnede1ta(2,
> d2 11 d1
3
>>> d1 // 2, d2 11 2

#
69120))
#

#
(datet1rne.tirnede1ta(1), datetirne.tirnede1ta(3, 43200))
> d2 % d1
#
datetirne.tirnede1ta(1)
>>> d1 * 2, d2 * 2
#
(datetirne.tirnede1ta(4), datetirne.tirnede1ta(14))

180

/.

Python 3j
i

#
>>> 2 * d1, 2 * d2
(datetime.timede1ta(4), datetime.timede1ta(14))
> d = -d1
> d, abs(d3)
(datetime.timede1ta(-2), datetime.timede1ta(2))

, n n

> d1
datetime.timede1ta(days=2)
>>> d2 = datetime.timede1ta(days=7)
>>> d = datetime.timede1ta(weeks=1)
>>> d1 == d2, d2
d
(Fa1se, True)
>>> d1 != d2, d2 != d
(True, Fa1se)
>>> d1 < d2, d2 <= d
(True, True)
>>> d1 > d2, d2 >= d
(Fa1se, True)

10.4.2.

date

'

==, ! =, <, <=, > >=.

date

datetime

n n n .

:
dt(<>,

<>,

<>)

n . n n
:

<> -

MINYEAR

R. :

>>> import datetime


>>> datetime.MINYEAR,
(1, 9999)

<>-

<> -

12

datetime.AXYEAR

n,

>>> datetime.date(2011, 8, 24)


datetime.date(2011, 8, 2~)
>>> datetime.date(2011, 13, 24)
# n
. . . n ...
Va1ueError: month must in 1 .. 12
>>> d = datetime.date(2011, 8, 24)
>>> repr(d), str(d)
('datetime.date(2011, 8, 24)', '2011-08-24')

Va1ueError. :

n n :

today () -

>>> datetime.date.today() #
datetime.date(2011, 8, 24)

1.

181

fromtimestamp(<Koeco >)- ,
, n n:

>>> import datetime, time


>>> datetime.date.fromtimestamp(time.time()) #
datetime.date(2011, 8, 24)
>>> datetime.date.fromtimestamp(1233368623.0) # 31-01-2009
datetime.date(2009, 1, 31)

fromordina1 (< 1 >) -

, n 1 . n 1

datetime .date.max. toordina1 ().

>>> datetime.date.max.toordina1()
3652059
>>> datetime.date.fromordina1(3652059)
datetime.date(9999, 12, 31)
>>> datetime.date.fromordina1(1)
datetime.date(1, 1, 1)
n :

+
+
+

year- ( n MINYEAR R);


month- ( 1 12);
day- ( 1 ).

>>> d = datetime.date.today() #
> d.year, d.month, d.day
(2011, 8, 24)
n

date

(24-08-2011)

n n:

date2 = date1 + timedelta- n n .


timedelta. seconds timede1ta .microseconds ;

date2 = date1 - timedelta- n .


timedelta. seconds timedelta .microseconds ;

timedelta = date1 - date2- (n ). timedelta. seconds timedelta .microseconds ;

n n .

>>> d1 = datetime.date(2011, 1, 19)


>>> d2 = datetime.date(2011, 1, 1)
>>> t = datetime.timede1ta(days=10)
>>> d1 + t, d1 - t
# N 10
(datetime.date(2011, 1, 29), datetime.date(2011, 1, 9))
>>> d1 - d2
#
datetime.timede1ta(18)
>>> d1 < d2, d1 > d2, d1 <= d2, d1 >= d2
(False, True, Fa1se, True)
>>> d1 == d2, d1 != d2
(Fa1se, True)

182 .
n

date

/.

Python 3

n :

replace ( [year] [, month] [, day]) -

n n n n

n. :

>>> d = datetime.date(2011, , 5)
>>> d.replace(2012, 3) #
datetime.date(2012, 3, 5)
>>> d.replace(year=2009, month=3, day=l)
datetime.date(2009, 3, 1)
>>> d.replace(day=7)
#
datetime.date(2011, , 7)

strftime (< >)

5)

isoformat () - --:
>>> d = datetime.date(2011,
>>> d.isoformat()
'2011-06-05'

strftime () time. :

>>> d = datetime.date(2011,
>>> d.strftime("%d.%m.%Y")
'05.06.2011'

5)

ctime () - n :
>>> d = datetime.date(2011, 6, 5)

> d.ctime ()
'Sun Jun

5 00:00:00 2011'

timetuple ()

struct_time

>>> d = datetime.date(2011, 6, 5)
>>> d.timetuple()
time.struct_time(tm_year=2011, tm_mon=, tm_mday=5, tm_hour=O,
tm_min=O, tm_sec=O, tm_wday=, tm_yday=156, tm_isdst=-1)

+ toordinal () - , n 1 :
>>> d = datetime.date(2011, 6, 5)
>>> d.toordinal()
734293
>>> datetime.date,fromordinal(734293)
datetime.date(2011, 6, 5)

weekday () -

n (- n,

):

>>> d = datetime.date(2011, , 5)
>>> d.weekday() # -
6

isoweekday()

~ n .

7 - ):

(1-

n,

10.

183

>>> d = datetime.date(2011, , 4)
>>> d.isoweekday() # -

t isoca1endar () -

(,

):

>>> d = datetime.date(2011,
>>> d.isoca1endar()
(2011, 22, 7)

10.4.3.

5)

time

time datetime .

time( [hour] [, minute] [, second] [, microsecond] [, tzinfo])


.
.
:

t
t
t
t
t

hour- ( 23);
minute-

59);

second- ( 59);
microsecond- 1 ( 999999);
tzinfo- ( tzinfo None).

Va1ueError.

>>> import datetime


>>> datetime.time(23, 12, 38, 375000)
datetime.time(23, 12, 38, .375000)
>>> t = datetime.time(hour=23, second=38, minute=12)
>>> repr(t), str(t)
('datetime.time(23, 12, 38)', '23:12:38')
>>> datetime.time(25, 12, 38, 375000)
...

...

Va1ueError: hour must

in 0 .. 23

t
t
t
t
t

h- (

23);

minute- ( 59);
second- ( ' 59);
microsecond-

999999);

tzinfo- ( tzinfo None).

>>> t = datetime.time(23, 12, 38, 375000)


>>> t.hour, t.minute, t.second, t.microsecond
(23, 12, 38, 375000)

184

/.

Python 3

time .

. :

>>> t1
datetime.time(23, 12, 38, 375000)
>>> t2 = datetime.time(12, 28, 17)
>>> t1 < t2, t1 > t2, t1 <= t2, t1 >='t2
(False, True, False, True)
>>> tl == t2, tl != t2
(False, True)

time

replace ( [hour] [, minute] [, second] [, microsecond] [, tzinfo])

. :
>>> t =datetime.time(23, 12, 38, 375000)
>>> t.replace(10, 52)
11
datetime.time(10, 52, 38, 375000)
>>> t.replace(second=21)
11
datetime.time(23, 12, 21, 375000)

isoformat ()

ISO 8601:

>>> t = datetime.time(23, 12, 38, 375000)


>>> t.isoformat()
'23:12:38.375000'

strftime (< >) - .

strftime ()

time.

>>> t = datetime.time(23, 12, 38, 375000)


>>> t.strftime ("%: %M:%S")
'23:12:38'

time

dst (), utcoffset ()

10.4.4.

tzname ().
tzinfo

datetime.

datetime

datetime datetime

. :
datetime(<o>,

<>,

<>[,

hour] [, minute] [, second]

[, microsecond] [, tzinfo])
.
.

+ <>- MINYEAR (1) R (9999);


+ <>- 1 12 ;

+
+
+
+
+
+

10.

<>-

185

hour- '! ( 23);


minute- ( 59);
second- ( 59);
microsecond- ( 99999);
tzinfo- ( tzinfo None).

valueError. :

>>> import date~ime


>>> datetime.datetime(2011, , 5)
datetime.datetime(2011, , 5, , 0)
>>> datetime.datetime(2011, , 5, hour=l2, minute=55)
datetime.datetime(2011, , 5, 12, 55)
>>> datetime.datetime(2011, 32, 20)
. . . n ...
ValueError: month must ~n 1 .. 12
>>> d = datetime.datetime (2011,. , 5, 5, 19, 21)
>>> repr(d), str(d)
( 'datetime.datetime (2011, , 5, 5, 19, 21) ', '2011--05 05: 19:21')
:

today () -

>>> datetime.datetime.today()
datetime.datetime(2011, , 24, 7, 51, 47,

now ( [<>] ) -

. ,

today () .

>>> datetime.datetime.now()
datetime.datetirne(2011, , 24, 7, 52, 14,

75000)

utcnow () - (UTC):
>>> datetime.datetime.utcnow()
datetime.datetime(2011, , 24, 3, 52, 39,

4)

90000)

fromtimestamp (< > [, <>] ) -

, :

>>> import datetime, time


>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2011, , 24, 7, 53, 14, 734000)
>>> datetime.datetime.fromtimestamp(12333B23.0)
datetime.datetime(2009, 1, 31, 5, 23, 43)

utcfromtimestamp(<Koeco >)- ,
, ,

>>> datetime.datetime.utcfromtimestamp(time.time())
datetime.datetime(2011, , 24, 3, 54, 2, 93000)
>>> datetime.datetime.utcfromtimestamp(12333B23.0)
datetime.datetime(2009, 1, 31, 2, 23, 43)

(UTC).

186

frornordina1

(<

/.

Python 3

>) - ,

. . 1

datetirne. datetirne .rnax. toordina1 ().

>>> datetirne.datetirne.rnax.toordina1()
352059

>>> datetirne.datetirne.frornordina1(352059)
datetirne.datetirne(9999, 12, 31, , 0)
>>> datetirne.datet~rne.frornordina1(1)
datetirne.datetirne(1, 1, 1, , 0)

comine ( <ru!

datetirne

date>,

<n

>>> d = datetirne.date(2011, , 5) # n
>>> t = datetirne.tirne(9, 12, 35)
# n
>>> datetirne.datetirne.comine(d, t)
datetirne.datetirne(2011, , 5, 9, 12, 35)

tirne>) -

strptirne (<,

>,

< >)

date

tirne:

date
tirne

, .
,

Va1ueError.

>>> datetirne. datetirne. strptirne ( "05. . 2011", "%d. %rn. %")


datetirne.datetirne(2011, , 5, , 0)
>>> datetirne. datetirne. strptirne ( "05. . 2011", "%d-%rn-%Y")
. . . ...
Va1ueError: tirne data '05.0.2011'
does not rnatch forrnat '%d-%rn-%Y'
:

+
+
+
+
+
+

year- ( MINYEAR R);


rnonth- ( 1 12);
day- ( 1 );
hour- ( 23);
rninute- ( 59);
second- ( 59);

rnicrosecod- (

tzinfo- ( tzifo None).

999999);

>>> d = datetirne.datetirne(2011, , 5, 5, 19, 21)


>>> d.year, d.rnoth, d.day
(2011, , 5)
>>> d.hour, d.rninute, d.second, "d.rnicrosecond
(5, 19, 21, 0)

datetirne :

datetirne2

datetirne1 + tirnede1ta-

datetirne2

datetirne1

tirnede1ta-

+
+

1.

187

timedelta = datetime1 - datetime2-

>>> d1 = datetime.datetime(2011, 1, 20, 23, 48, 23)


>>> d2 = datetime.datetime(2011, 1, 1, 10, 15, 38)
>>> t = datetime.timede1ta(days=10, minutes=10)
>>> d1 + t
# 10 10
datetime.datetime(2011, 1, 30, 23, 58, 23)
>>> d1 - t
# 10 10
datetime.datetime(2011, 1, 10, 23, 38, 23)
>>> d1 .- d2
#
datetime.timede1ta(19, 4875)
>>> d1 < d2, d1 > d2, d1 <= d2, d1 >= d2
(Fa1se, True, Fa1se, True)
>>> d1 == d2, d1 != d2
(Fa1se, True)

date ( J

datetime

>>> d = datetime.datetime(2011,
> <;l.date(J
datetime.date(2011, , 5)

time ( J -

+
+

date:

5, 23, 48, 23)

>>> d = datetime.datetime(2011,
> d.time()
datetime.time(23, 48, 23)

time:

5, 23, 48, 23)

timetz ( J - time. tzinfo;


rep1ace( [year] [, month] [, day] [, hour] [,
tzinfoJ J -

minute] [,

second] [,

microsecond] [,

. :

> d = datetime.datetime (2011, , 5, 23, 48, 23)


>>> d.rep1ace(2008, 12)
datetime.datetime(2008, 12, 5, 23, 48, 23)
>>> d.rep1ace(hour=12, month=10)
datetime.datetime(2011, 10, 5, 12, 48, 23)

timetup1e () - struct_time :
>>> d = datetime.datetime(2011, , 5, 23, 48, 23)
>>> d.timetup1e()
time.struct_time(tm_year=2011, tm_mon=, tm_mday=S, tm_hour=23,
tm_min=48, tm_sec=23, tm_wday=, tm_yday=15, tm_isdst=-1)

utctimetup1e ( J (UTC):
.

>>> d = datetime.datetime(2011,
>>> d.utctimetup1e()

struct time
-

5, 23, 48, 23)

188

1.

Python 3

time.struct_time(tm_year=2011, tm_mon=6, tm_mday=5, tm_hour=23,


tm_min=48, tm_sec=23, tm_wday=6, tm_yday=156, tm_isdst=O)

toordina1 () -

1 :

>>> d = datetime.datetime(2011, 6, 5, 23, 48, 23)


>>> d.toordina1()
734293

weekday () -

6-

):

>>> d = datetime.datetime(2011, 6, 4, 23, 48, 23)


>>> d.weekday() # 5-
5

isoweekday () -

(1-

7 - ):

>>> d = datetime.datetime(2011, 6, 4, 23, 48, 23)


>>> d.isoweekday() # 6-
6

(,

isoca1endar () -

):

>>> d = datetime ..datetime (2011, 6, 5, 23, 48, 23)


>>> d.isoca1endar()
(2011, 22, 7)

isoformat ( [<>]) - ISO 8601:


>>> d = datetime.datetime(2011, 6, 5, 23, 48, 23)
>>> d.isoformat()
#
'2011-06-0523:48:23'

>>> d.isoformat(" ")


'2011-06-05 23:48:23'

ctime () - ~:
>>> d = datetime.datetime(2011, 6, 5, 23, 48, 23)
>>>d.ctime()
'Sun Jun 5 23:48:23 2011'

strftime (< >) - .


,
strftime () tirne. :
>>> d = datetime.datetime(2011, 6, 5, 23, 48, 23)
> d.strftime("%d.%m.%Y %H:%M:%S")
'05.06.2011 23:48:23'

datetime astimezone (), dst (),


tzname (). ,
tzinfo datetime.

utcoffset ()

10.

10.5.

calendar

189

calendar.

. ,
:

import calendar
n :

Calendar-

, .

Calendar([<nep

>])

n n n

no

2011

, n

>>> import calendar


>>> = calendar.Calendar(O)
>>> c.monthdayscalendar.(2011, 4) # 4 -
[[0, , , , 1, 2, 3], [4, 5, , 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30, ]]

Textcalendar-

n n .

TextCalendar([<nep


>>>=

>])

2011

c~1endar.TextCalendar(O)

>>> print(c.formatyear(2011)) #

LocaleTextCa1endar-

2011

n n .

.
:

Loca1eTextCalendar([<nep

>[,

201 1

< >]])

>>> = ca1endar.LocaleTextCalendar(O, "Russian_Russia.1251")


>>> print(c.formatyear(2011))

HTLCalendar

HTMLCalendar([<nep

HTML.

>])

201 1 :

>>> = calendar.HTMLCalendar(O)
>>> print(c.formatyear(2011))

Loca1eHTLCa1endar- n

HTML.

.
:

LocaleHTMLCalendar([<nep

>[,

< >]])

190

2011

/.

Pytho

>>> = ca1endar.Loca1eHTMLCa1endar(O, "Russian_Russia.1251")


> xhtm1 = c.fonnatyearpage(2011, encoding="windows-1251")
>>> print(xhtm1.decode("cp1251"))
n ( n) 6
( ). , .
n

SUNDAY.

MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY


setfirstweekday (<

n n

>). n

(
:~~~~~~
:

2011

. n

10.3).

.:;ii:i. 8~;$;;A~~~~~~ci~~~~~~~p~. :. . . . .: . . . . . . . .: . . . . . . . . . . . . . ._. .,. . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . .:

.............................. .......,.............................. ...;,.,.,,,;,................................ ;,;,,,,,,,,,,;,.,,;,;;;,,; ...........................;.; .. ...;;,,;,,, ......... ;................................................


;

..

>>> = ca1endar.TextCa1endar()
#
>>> c.setfirstweekday(ca1endar.SUNDAY) #
>>> print(c.fonnatmonth(2011, 1)) # 2011 .

10.5.1.

TextCa1endar

fonnatmonth(<o>,

<>[,

TextCalendar Loca/e TextCalendar

Loca1eTextCa1endar

< >[,

<

> J J) ~ . n
n ,

n .

2011

>>> import ca1endar


>>> = ca1endar.Loca1eTextCa1endar(O, "Russian Russia.1251")
>>> print(c.formatmonth(2011, 4))
2011

4 5 7 8
11 12 13 14 15
18 19 20 21 22
25 2 27 28 29

2 3
9 10
16 17
23 24
30

prmonth (<>, <> [, < > [, <


> J J ) ~ fonnatmonth (),
~!, .

2011

>>> = calendar.Loca1eTextCa1endar(O, "Russian Russia.1251")


>>> c.prmom:h (2011, 4' 4)
2011

11
18
25

5
12
19
2

13
20
27

7
14
21
28

1
8
15

2
9

3
10
17
24

22

29

23
30

10.

formatyear(<o>[,

191
=]

w=2] [, 1=1] [,

[,

m=J)-

. :

w-

1 -

- ( );

m-

2);

1);

( ).

201 1 .

>>> = ca1endar.Loca1eTextCa1endar(O, "Russian_Russia.1251")


>>> print(c.formatyear(2011, m=4, =2))

rr(<>[,

w=2] [, 1=1] [,

=]

[,

m=])-

fonnatyear(),

, .

2011 .
4 , 2 ,

>>> = ca1endar.Loca1eTextCa1endar(0, "Russian_Russia.l251")


>>> c.pryear(2011, 2, 1, 4, 2)

10.5.2. HTMLCalendar LocaleHTMLCa/endar


HTLCa1endar Loca1eHTLCa1endar :

formatmonth (<>,

<>

[,

<True

Fa1se>]) -

L-

True

), .
L-.
, ~ .

cssc1asses,

>>> import ca1endar


>~> =

ca1endar.HTLCa1endar(0)

>>> print(c.cssclasses)
1
[
mon 1 , 1 tue 1 , 1 wed 1 , 1 thu 1 ,

-

>>>
>>>

fri

2011 .
"week-end":

sat 1 ,

sun 1 ]

"workday",

= ca1endar.Loca1eHTMLCa1endar(0, "Russian_Russia.l251")
cssc1asses = [ "workday", "workday", "workday", "workday",
"workday", "week-end", "week-end"]
>>> print(c.formatmonth(2011, 4, Fa1se))

formatyear(<o>[,

< >])- HTML-K<J?leHap

. L
.
:

2011

192

/.

Python 3

>>> = ca1endar.Loca1eHTLCa1endar(O, "Russian_Russia.1251")


> print (. fonatyear.(2011, 4))

fonatyearpage (<>

[,

width] [,

css] [, encoding] ) -

L-

L-.
n:

width- ( 3);

css- ( "calendar. css");

encoding- . n
encoding L-n, <meta>.

n n n n
n. n

2011

>>> = calendar.Loca1eHTLCalendar(O, "Russian_Russia.1251")


>>> xhtm1 = c.fonatyearpage(2011, 4, encoding="windows-1251")
>>> type(xhtm1) # bytes
<c1ass 'bytes'>
>>> print (xhtm1.decode ("1251"))

10.5.3.

calendar n , n

n , n
:

setfirstweekday(<ep

>) - n

. n ( n) (
). n MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY SUNDAY. n
n firstweekday (). n :

>>> import ca1endar


>>> ca1enctar.firstweekday()

>>> ca1endar.setfirstweekday() #
>>> ca1endar.firstweekday()
#

month(<o>,

<>[,

< >[,

<

> J J) - . n
n n , n-

n . n

>>> calendar.setfirstweekday(O)
>>> print(ca1endar.month(2011, 4))
Apri1 2011
Tu We Th Fr Sa Su
1

11 12 13 14 15

10
17

2011

2011

10.

193

18 19 20 21 22 23 24
25 2 27 28 29 30

prmonth (<>,

<> [ ,

<

> [ ,

<

> J J) - month (),


, . n

>>> ca1endar.prmonth(2011, 4) #

monthca1endar (<>, <>) -

2011

20 11

, n .. , n ,
n . n

2011

>>> ca1endar.monthcalendar(2011, 4)
[ [0, , , , 1, 2, 3], ,[4, 5, , 7, 8, 9, 10],
[11, 1_2, 13, 14, 15, 1, 17), [18, 19, 20, 21, 22, 23, 24],
[25, 2, 27, 28, 29, 30, 0))

monthrange (<>,

<>) -

>>> print(ca1endar.monthrange(2011, 4))


(4, 30)
>>> #

2011

30

ca1endar (<> [, w] [, 1] [, ] [, m] ) -

. n:

w - n (

1 -

- n ( );

m-

2);

n (

1);

3).

n n n n
n. n

2011

n
:

>>> print(ca1endar.ca1endar(2011, m=4,

prca1 (<> [, w] [,

1 J [,

) [,

m) ) -

=2))

ca1endar (),

, . n

2011

, n

n :

>>> ca1endar.prca1(2011, 2, 1, 4, 2)

is1eap (<>) -

True, ,

n -

Fa1se:

>>> ca1endar.is1eap(2011), calendar.is1eap(2012)


(Fa1se, True)

1eapdays (<1>,

<2>) -

<1> <2> ( <2> ):


7 . 1349

194

>>> ca1endar.1eapdays(2010, 2012) # 2012

1.

Python 3

>>> ca1endar.1eapdays(2010, 2013) # 2012-

weekday(<o>,

<>,

<>)- (-

, - ):

>>> ca1endar.weekday(2011,

4)

timegm(<OOe

struct_time>) -

, .

struct_time
gmtime () time. :

>>> import ca1endar, time


>>> d = time.gmtime(130352099.0) # 23-04-2011
>>> d
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=23, tm_hour=1,
tm_min=4, tm_sec=59, tm_wday=5, tm_yday=113, tm_isdst=O)
> tup1e(d)
(2011, 4, 23, 1, 4, 59, 5, 113, 0)
>>> ca1endar.timegm(d)
130352099

>>> ca1endar.timegm((2011, 4, 23, 1, 4, 59, 5, 113, 0))


130352099

ca1endar :

day_name- :
>>> [i for i in ca1endar.day_name]
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday']

day_abbr- :
>>> [i for i in ca1endar.day_abbr]
['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

month_ name -

>>> [i for i in ca1endar.month_name]


['', 'January', 'Febr:try', 'March', 'Apri1', '', 'June',
'Ju1y', 'August', 'Septemer', 'October', 'Novemer', 'Decemer']

month_abbr- :
>>> [i for i in ca1endar.month_abbr]
[ ' ' , 'Jan' , 'Feb' , 'Mar' , 'Apr' , : ' , 'Jun' , 'Ju1' , 'Aug' ,
' Sep ' , ' Oct ' , ' Nov' , ' Dec ' ]
>>> import 11 #
>>> 1oca1e.set1oca1e(1oca1e.LC_ALL, "Russian_Russia.1251")
'Russian Russia.1251'
>>> [i for i in ca1endar.day_abbr]
[ ' ' , ' ' , '' , '' , ' ' , '' , '' ]

10.

195

>>> [i for i in calendar.month_name]


'

[' ' ,

'',

',

''

'',

''

'',

'n

',

'',

>>> [i for i in calendar.month_abbr]


[' ', '', '', '', '', '',
' ' , '' , '' )

''

'.'

''

'']

'',

'n',

'',

'',

10.6.

t.imeit

. .
:

from timeit import Timer


imer.

Timer( [stmt='pass'] [, setup='pass'] [, timer=<timer function>])


stmt ( ),
setup ,
stmt. , setup

timeit 1[numer=1000000J).

numer ~ .

, .' " ' .... ' . ' . ' "

r..

" '

. . . . . . . ' " . " ' ' " ' . " . . . . "

. . . " ' .. "

.. ' " ' . , " , "

......... "

.. " , .. "

. . . . . . . ~" . . . " . . . . t ' " .. ' " ' ~ . . . . . , " . : ' . . . ~ ..

! ...: t . . . " ' .. ' .. " " ' .......... ~ ., ' ' : . . . . . . ' .. " " . . . . . . , "

.... "

.. "

.. " " .. " ' " " . ' ' " . " .

.~~~~... ~.~.:~:. .~.~-~.~.~~~.~~. ~.~~~.~. ~.~~~~~.~.~-~~~. :. . . .;. . . . . . . . . ,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .;. . . . . . . . . . . . . . . . . . . . .1

# -*- coding: utf-8 -*from timeit import Timer


codel = """\
i, j = 1,
while i < 10001:
-t=

+= 1

t1 = Timer(stmt=code1)
print("whi1e:", t1.timeit(numer=10000))
code2
"""\
j

10000 n n n ( 10.4) .

for i in range(l, 10001):


+= i

t2 = Timer(stmt=code2)
print("for:", t2.timeit(numer=10000))
code3 = """\
j = sum(range(1, 10001))

196

/.

Python 3

t3 = Timer(stmt=code3)
print("sum:", t3.timeit(numer=10000))
input ()
( ):

while: 17.26802443580117
for: 9.602403053818772
sum: 3.067899091205735
,

for whi1e, sum ()

repeat([repeat=3] [,

numer=1000000])

repeat)

timeit()

. numer

t imei t ().
10000.

for append (), - ( 10.5) .

......... ,..... ,... ,, ... ,... ,......... " .... ,, ................. ,, ... ,, ............................. ,._,,.,,.. ,, ... ,,, .. ,, ......... ,t.''''''''''''''''''''''.:"''':,."'''"'''''''''''''

[. 10.5. l1n;~~~ ~t
;, ........................................................... ...... .. .... .....................;.;: ................................................. :.....................................; .... .
;

:.~

# -*- coding: utf-8 -*from timeit import Timer


code1 = '"' "\
arr1 = []
for i in range (1, 10001):
arr1.append(str(i))

t1 = Timer(stmt=code1)
print("append:", t1.repeat(repeat=3, numer=2000))
code2 = """\
arr2 = [str(i) for i in range(1, 10001)]
t2 = Timer(stmt=code2)
t2.repeat(repeat=3,
input ()

print("eepaop:",

numer=2000))

append:

[9.98154294362325, 9.997541285814483, 10.004275691347512]


[7.879446040575054, 7.924527742041953, 7.844603314867392]

, .

11

- , n. n
n
n, n

Python,

len () n n.

n n .

11.1.

n n

def

< >

["""

def no

( [ <>] ) :

"""]

< >

[return

<>]

, ,
n, n .
n , , n
.
.

n
n. n n, n
. .

. ,
n .
, n n.
, n pass.
n n n n, n
, n n. , :

def func ():


pass

return n . n

n . ,
n n

return

n.

198

/.

Python 3

def func():
print (" return")
return " "
print ("
print(func()) #

m")

return

return

None.

def prlnt_ok():
""" n """
print (" m
def echo (m) :
"""
print(m)

def summa(x, ):
""" "

return

11.1 ).

")

"""

.,

, 1 .
,
, .

:"~".''~" "~

11.1

11.2.

" ''~!' ''~"'''"'' "''' '" "~" . '"'''"'"' '~"'"" ''~" .'.'"' '.'"' '~" """' ~ '.'.''

1.:~-~~.~ci~.:.~~-~-~?;~.ffir~:~~~;;,.;,_:;
print_ok ( 1
echo ("")
= summa(S, 2)
, = 10, 50
= summa(a, )

#
#
#

7
60

,
. , ?
, . .

. , , -

11.

199

wt11 n . n

11. 9.

n +, n sUJ111a

( 1,

n ,

n n. , sUJ111a

(1

n . n n

n:

def

SUJ111a (,

):

return

print ( sUJ111a ( "str", "iQg" 1 1


#
print (sUJ111a( [1, 2], [3, 4])) #
,

string

[1, 2,

Python

3, 4]

, n , n

n . .

def ,
function, , n
def. , n

. .
n (

11.3) .

.................................................................................. "'"""~"'''"'''~~"'""'""'''"''""''''''''''''"''"''""'"""""'"'"' ... ''"'"''''''"''''""''"""'''"'"''"'""""''''''"'"'"""''''''"'"'""'"'''''""~''"'""'>

[ 11.3. cct:.U1k ~:~ i . nf!~~


i
;;, ..................................
............... ..........................
... :..
.. ;,;;,,,,,... :... :: .................:...:....... :.;,.,;,,;,,,,,::....;.;;,;,;;,,:,;;;;,,,:....:...;............. ............ .................................. ;
def SUJ111a (, ) :
return +
,,.;;

f
v

,,;;,,,;,~

#
#

sUJ111a

f(10,

;;;;~;;;;:;,,

20)

..;

n n .
,

11.4).

no

, (

c~~~~~F<~:~::~~. !i~:~:~~~::~~~:~iF~~?.::~~~~~~:.:.:::~:::~:::.:.:.:::.:::.:::.::::::.:.::::::.::::::::::::::::::::::::::.::::.:::::::::. : :.: :.: : .: : .: .:.: .:.: . .:. :. : . : :. : .,_: : : : :~


def

sUJ111a (,

) :

return

def func(f, ,
"""

):

l.I.

return f

f m
s UJ111a ( 1 " " "
) # SUJ111a ()

(,

func(summa, 10, 20)

11 n .
n . n, _n_

n , 'i

_doc_ -

. . n n

dir ( 1:

200
>>> def summa(x,

/.

Python 3

):

""" ~
return +

"""

>>> dir(summa)

closure
annotations
call
class
code
dict
doc
_eq _
defaults
delattr
_ getattribute
fonnat
ge
_get
globals
kwdefaults
hash
init
le
lt
gt
new
module
name
ne
reduce
setattr
sizeof
str
repr
reduce
suclasshook
']
>>> summa.
name
['

'surnrna'

>>> summa.

( '',

>>> summa.

'

code

varnames

'')

doc

11.2.

'

n n n . ,
n n n, n n
, n . n n
n .
:

def summa(x, ):
return +
v = summa(10, 20) #

n:

v = summa(10, 20)
def summa (, ) :
return +

' 11

n "NameError: name 'summa' 1s


not defined". , n
n n n , .
..

n n

if n n n1.

, n
, (

11.5).

, .. .. .. "000"'''''"00'<""'"''''''''''"'''"'''"'""'''"'""'''"'''"'''"'''''''"''""'''"'""'''"'''"'""'"'''"''''''''""'""'""'"''"'00 .. '000""'''""''''"''''"''''"'''"''"'''"'''"''"''''""""''"' '"''"'0000<000''000,_000""0

l ...............................................................
11.5. n ~tr or
........... ............. .................. ........ ........ ...... .. ..... ...................... ............................. ..................................................................... :
;.,

;;,,;,,

':

~ ;.;

-*- coding: utf-8 -*-

n = 1nut(" 1
n = n.rstrip("\r")

")
3.2.0

(.

1.7)

11.

201

ifn=="l":

def echo():
print (" 1")
e1se:
def echo():
print ( " ")
echo ( ) #
input ()

"

1",

" ".

def

def.
, ,

. :

def echo():
print (" 1")
def echo ():
rint(" ")

echo() #

11.3.

" "


,
, .

def

sumta (,

=2):

return +
= sumta (5)

50)

sumta(10,

11.6).

#
#

60

, , 2.
, n
, .

n n n :

def

sumta (,

return

print(sumta(10,

20))

30

n n n

10, n -
20. Python n n , n
( 11.7). n n n
. n n.

202

def summa(x, ):
return +
print(summa(y=20,

=10))

/.

Python 3

,
. ,
. :

def summa(a=2, =3, =4): #


return + +
print(summa(2, 3, 20))
#
#
print(summa(c=20) 1
, ,
, *.

1 1.8.

!~~~-~~.11:~:,.~~~~~--~~~~~~:~~~-~~~-~;~~;~~-~-~ri~.;~~-

. ......~: ~ ~; ....... ,;.,. ,,;; ........... :... ,;, ;;., ;, :.<....:.... i . :. : ;,;, ,;;,; :~ ;;;:. ,, : ,; :::.: ~ :: :: ;:. :...~ : ...; :;. ::.... ,.; ,:;.......; ;;,; ,; ,,;, .. : .:. : .... : ' ........ ". ....... . .. .. . .. ..

~ ~

def summa(a, , ):
return + +
t1, arr = (1, 2, 3), [1, 2, 3]
print(summa(*t1))
print(summa(*arr))
t2 = (2, 3)
print(summa(1, *t2))

#
#

' . "' ....... ' .. " .... " ...... '.'

, ,

(**) (

1 1.9).

:~;;;~~;11":9;~~~~~ ~~~~4~~~4iii~tJ~~h~~~~~::::_
;,;,;,;;,.;,;,;

. . . . ,. . . . . .,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . !

......... ...,..;, ..................................... ...., ........ ;... :..;/:.,'...:.. ...;,;,.;,,::... :..........:;;... :............. :...... .................. ................ ...................,..............................................................
~

;;.~;.,

def summa(a, , ):
return + +
dl =

{"":

1,

"":

2,

"":

3}

print(summa(**d1))
t' d2 = ( 1' 2) ' { "" : 3}
print(summa(*t, **d2))

. ,
u:

def func(a, ):
, = 20, "str"
,

= ,

func (, s)
print (, s)

''test''

#
#

test

, :

11.

def func

(,

[],

[1, 2, 3]

{"":

func(x,
print (,

[""]

1,

203

"":

"str", 800
#
2}
#
#

#:

'

['str', 2, 3]

!!

{'':

800,

'':

2}

n, , . .
n. ,
(

11.1 0) .

.......... , ................... ,... , .... ,., ...... , ..... ,., .. ", .. " ..... , ........... ,.".,.".,.,"... ,",.,,." ........ " . "., .. ": .. ,",~",,,... ,!''"!''":'<!."'''"

... ~, .... ~~-,:~:;:""':::"''''\~"''''~

::~,::;:~:"''"'''''''

i:.....................................................
1110. ~ o~1"~.ta/$yt{~q\fiO. ..
;.................... :.........~....;;........ ;.... ,..;,;'...........:.. ~;; .... ;.;, .....;;......... ;. ,i.:........~ ........ :.~..=:.~; :. :.:.....:.......................... :. ::............. .. :.... :......:.~: . :....... ,. .: .. ,, 1
def func(a, ):
[:]

~ . ()
[0], [""]
=
[ 1' 2, 3]
~

{"":

func(x,
print(x,

1'

"":

#
#

#
#
#
#

"str", 800

2}

)
)

[ 1' 2, 3]

{'':

1'

'':

2}

func(x[:],

.())

, , ,
. :

def

func(a~[]):

a.append(2)
return
print ( func () )
princ (func ( 1 1
print ( func () )

#
#
#

[2]

[2,

2]

[2,

2, 2]

, .
, , :

def

func(a~None):

#
if

None

[]

a.append(2)
return
print(func())
print (func( [1]))
print ( func 1) )

11.4.

is None:

#
#
#

[2]

[ 1' 2]

[2]

*,
.

204

1.

Python 3

.
(

11.11).

def summa(*t):

res =
#
for i in t:
res += i
return res
#
print(summa(10, 20))
print(summa(10, 20, 30, 40, 50, 60))
#

:
:

"""

30
210

,
:

def summa(x, y=S, *t): #


res = +
for i in t:
#
res += i
return res
print(summa(10))
# : 15
print(summa(10, 20, 30, 40, 50, 60))
# : 210

(**),
(

11.12) .

................................................................."''''"'''"'"''''''''"'""'""'"'''"''"'"'''"'''''"''''''""'""'"'""'"'"'''"''''''''"''"'''"'""'"'''"'""''''"''''''''''''"''
I r 11;12. ~ n

...............................................................;,. ~;::.:..~ .....;;;,:. .....~. ;;.~. . ,.,. ;.:::..... :.:............................ :.....::.. :: ................. :.. ::....;.: ....... ;.;,,,,;,,;,,,,,,,,, ............. :...:. ......................................... J
def func(**d):
for i in d:
# ~
print("{O} => {1}".format(i, d[i]),. end=" ")
func(a=1, =2, =3) # : => 1 => 3 => 2

.
, (
11.13) .

... ' ..... " ,.. '."'".'' ... '' ... '." ... " ..... ".""'""."".' .... " ..... "."" ...... ""' .. " ... " ...... "., ......... '" ....... ,.. "" ........ " ... " .... '' .... '.'"' ............... " .... ''"" .... """' ... "' ........ '.' .'' .. " ... "' .. " ... "' .. "' .. " . ' "'.'"' .. "'".''
t 11.1 ~. t<t.4 napaJ\II~rpo~
,!
:.................... ;.............. :.,.::..~~.: ... ;,,;,,;,,.................................................:.....~......'...::;;;,;,...........;; ............ ;;..~............ ;:.~ .......:.. ;:....... ;;:...;.,;: ..:...............................................................:1
~:

def func(*t, **d):


"""
for i in t:
print(i, end=" ")
for i in d:
#
print("{O} => {1}".format(i, d[i]), end=" ")
func(35, 10, =1, =2, =3) # : 35 10 => 1 => 3 => 2
func (10)
# : 10
func(a=1, =2)
# : => 1 => 2

11.

Python 3

205

.
, .
. :

def func(*t, , =10, **d):


print(t, , , d)
func(35, 10, =1, =3) # : (35, 10) 1 10 {'': 3}
func(10, =5)
# : (10,) 5 10 {}
# : () 1 2 { }
func(a=1, =2)
func (1, 2, 3)
# . !
t ,
. ,

.
, ,
,

=.

d .
, ,
.

,
, ,
. ,

, ,
:

def func(x=1, =2, *


'
print(x, , , )
func(35, 10, =1)
func(10, =5)
func(a=1, =2)
func(a=1, =, =7)
func(1, 2, 3)

#
#
#
#
#

=10):

35 10 1 10
10 2 5 10
1 2 1 2
7 1 10

:
:
:
:

,
. ,
. ,
.
, ,

, .

11.5.

Python

-.
lamda :
lamda

[<l>[,

... ,

<N>]]:

<

>

lamda .

<

>

. , - .
.

206

f.

Python 3

- -,
.
- , , ,
. -

11.14.

~~~-~:1.1/14:~~~;~,-~~ri6ri~~~~~~;;;;~~:;~~4;}i

.........................!

i ............... ,,,;;, ......................................................; .. .,,,,.,,,;,;,;,,,,, .. ,; .. ,,,; ........ ; .. ,,;,;;;,,,,,,,, ............................... ; ....... ;;,,;,,,.,,...........................................

1amda:

fl

10 + 20

f2 = 1amda , : +
f3 = 1amda , , z: +
print (fl ())
prim: (f2 (5, 10))
print(f3(5, 10, 30))

#
#
#
#
#
#

+ z

JJ.

JJ.

JJ.

. ............................. .

30
15
45

:
:

, -

.
(

11.15).

!"
11.1s. 38l ri$ -.
... ;, .... " ... " .....................
,;, ......... ...................... ;, .;, ..... ,; :. ... :. ::. ,; ,:,; ,;;:;
.. .......... ...... .. ;., .. ............... :,; .... .. .... ,; . :. ..... """:"" ...... .' .................. " ...
;

'

',;,.'

f = 1amda ,
print (f (5))
prim:(f(5, 6))

~-. ;,

;,

=2:

'

;,

,:, ;

;,

'.

#
#

:
:

7
11

,
. ,

key.

sort ()

- (

11.16) .

.................. .... ............... ......... ........................................................................................... ................................................................................................................................................... :


~

i:.................................................................
~t 11, 16. ) r:
....:.......... ...............:.......... .........:........ ................................................. .......... ........ ............................................................................. :
,;

arr =

["1",

"",

".

"2"]

s: s.1ower())
for i in arr:
print(i, end=" ")
# m: 1

arr.sort(key=1amda

11.6.

- ,
.

yie1d.

11.17) .

................................................................... ., ............ !''""~~"~'!~"'''"''""'":'"~""''".'":'!''"'"""~""'''"~""''"''"'"""''!"""'''"''"'""''"'"''"""'"'''''"'"'.''""'"'''"'"''"""'''""''''''""'''''''"''"''''

[ 11.17 cnoS1~C)~!flii -
: ................. ........... .. ........... .......... ... ......... ;,,.,:,;,;,;, .. .;,; ... ......... .. ........,;.. ;,;......... ,...... ; .. .......; ....... ;...-:.................. :....-..................... :...........................
~

; ~

;;

def func (, ) :
for i in range(1, x+1r:
yie1d i **

,;

;;

~;

,,,,.,

...... ...................... ..........


;

11.

for n in func(10, 2):


print(n, end=" ")
print ( 1
for n ir. fur.c(10, 3):
prir.t (n, end=" ")

#
#

rn:

207

1 4 9 16 25 36 49 64 81 100

1 8 27 64 125 216 343 512 729 1000

u-

Stopiteratior..

_next_ ( 1,

( 1 u for .
_ next _ ( 1
u for ( 11.18).

def func(x, Yl:


for i ir. range(1,
yield i **
i = func(3, 3)
print(i. next
print(i. next
prir.t(i. next
print(l. next

next

+1):

#
#
#
#

())
())
())
())

1 (1 ** 3)
8 (2 ** 3)
: 27 (3 ** 3)
Stopiteration

:
rn:

, u 'l ~ '
, u- .
, . .
.

11.7.

u. , '
-

u.

1 1.19) .

..................... ,._ .............................................................................,.......................................................... ............................ ..._,.,... ... .............................................................................. .


_

1. ~-~~~~.... ~ ~ :.~.~.~ ~..~.~~!.~...~~. !~~-~~~~

return f
@deco
def func () :
return "

= 10

func ()

func()")

(O}".format(x)

print (func (10))

. .: :~;, .;, : . . .:. . . . , .:. : :,:. ;.: . : . . . :. . . . :'. .;'.::(.:,.:;. "'................... . . . . . . . . :. . . . . . . .:. . . . . . . . . . . .J

def deco(f):
print("Braa

~.,.~,

208

1.

Python 3

func () deco ()

@:

@deco
, deco () func ().
- ,

. - .
:

def deco (f):


rint("

return f
def func () :
return "

{O}".forrnat(x)
func ()
(deco (func) (10))
=

pnt

func()")

deco ()

-.

func ()

decol ()

deco2 ( 1 (

11.20).

l;.................................
11 .20. '~ 11~ ..
;...........
.. ;:,;,,,,,,,,;;,;,,;,,;,,,,.....................................................................,..;,,,,;,,,.,,:,;;,,,...................... :.............................................................!
,,,;,,,,,;,,,,,,,,,;.;~

def decol(f):
print (" decol () ")
return f
def deco2(f):
print (" deco2 () ")
return f
@decol
@deco2
def func () :
return "
{O}".forrnat(x)
print(func(10))
:

deco2 ( )
decol ()

= 10

func = decol(deco2(func))
deco2 (), decol ().
func.

(

passw
input (" : ")
passw = passw.rstrip("\r")
#

3.2.0

11.21 ).

11.

def test_passw(p):
def deco (f) :
if == "10":
retur f
e1se:
retur

1amda:

@test_passw(passw)
def func():
return "
print(func())

"

return deco

209

"

"

n @ , ,
. ,
n (

deco 1) ).

test_passw 1),

n n,

func 1), n n "

", .

11.8.

Peypczm- . n

n , , n n

n. n
(

11.22).
..................... "' .......... , ...

................................... :.........:...................:........ ;...... :............. ;........ ;.... ;.; ......:....

~:;;;,.,,;;

................ ;; ..;.:,,; .....................................................................................................

def factoria1(n):
if n == or == 1: return 1
e1se:
return n * factoria1(- 1)
whi1e True:

= inut("
= x.rstrip("\r")

rint("

factoria1 1)

#
#
#

it(x)

break
e1se:
print ("

{0}

(.

1.7)

!")

{1}". fonnat

2.6,
math. :

>>> import math


>>> math.factoria1(5), math.factoria1(6)

(120, 720)

3.2.0

if x.isdigit():

")

(,

factoria1

()))

'

210

11.9.

/.

Python 3

.~t-

Pytho , (

11.23).
'" "~

f. 11.23. rQ6(1 !J , .. .

:..................................................... .............;:...... :......... ;,.,.:;........... ; ...... ; .. :....:..................................................................................................................................................


;

def func(g1ob2):
rint("

g1ob2

+~

n g1

~",

glo)

10

r1n1::("

g1ob2

~",

g1ob2)

g1ob2 ~ 10, 5
func(77) #

glo,

rint("

g1ob2 -"

g1ob2)

= 10
g1ob2 ~ 87
g1ob2 ~ 5

g1

g1ob2 ,
g1ob2, 1..

ll nepti!JIIIe- ,
. ,

,
.

(
1

11.24).
11;24: nri1 n~~1

;,,,.,,,.,.,,,,.,.,,,.,,,,.;,,,,,,;,.,,,",;,,,,.;,;,';._,,,,,;,,,,,.,;~;,,,v;,,,~;.,,,,.,,~,,;,,;,,.~;,,;,,,,,.;;,,,;,,. .,,.~ ..... .,,.,,,.,.;,.,~ .. ,,.,;,,..,;;,.,,.,,,,,~,,,",..,,,..,,.,,.,,,.,,,,.,;;,..,.,,.,,,.,,,,..,,,.,,,,~,,,,,,,,.,.,,,..,,,.,,,.,,,,,,.,,,,,,,,

def func! 1:
loca11 ~ 77
g1 = 25

#
#

rint("

g1

~ 10
func ()
print (" g1
try:
print ( 111)
except NameError:
rint("

#
#

-"

g1

g1

#
#
111

111

25

10

g1)



g1)

=",

g1

NameError

rn

")

'"""''""""'

211

11.

locall, func (),

. glo
.

UnboundLocalError

),

11.25) .

............... ,......... ,................ ,........ ,.......... ,.,.,., ... ,.............. ..,.,.,. ....................................................,... " ....... ,....,., ... ,.. ," ......... " ........... " ......................,.......... ,..... "., .......... ,, .. ,......... ,..

~- 11.25. n n n ~

'

:..................... :......................................................... :.......... ;.: .....:..... :.. :.......... ;:.:.:.:::.:::::::.;,;,:,,;:-... :.'.'.i.>; .=;,;;.~:: ..... :: ......... ;.: ........... :................... :..................... ;:,.. ..:........ ~

def func ():


#

#
#
#
#

printlglo)
glo
glo

~25

lO

funcl)
#

UnoundLocalError:

ll!!

!1

m:

local

variae

'glo'

referenced before assignment

I J ,


(
:'"'''"'''"""~"'"''''~

......................... .............. .... .......... .......... ................................... ...............................,......... ... ..... ....
~

global.

11.26).

ttr 1.1.26. n~ glI>

~~~.~~

-; '

............ ................................... ................................,


~

,~

: .... " ... ". ''" .. " .... " ........ "' . " ...... ,; ;, ;;, i....:.: ;.: .. :::." .... " ... ' . :.. :.. :.. ;.... ""' ..:; :.. ;~: .. ;." .. ". :."...:.; ',;;.,; .. '. '" .. '". :: ;, '. :.. ;".: ;;:;; ... 1; .. ,,; {il i.; ,.,; ;;,=~; ;, ;,; :~ .... '""" . "" .. '." ... ,, "" ..... "." .... " ... :. ;... "' ..... ;, ....... ~

def funcl):
# glo
global glo
glo ~ 25
#
rit("

glo

glo

lO

rintl"

func 1)
print 1"

#
glo

~",

glo)

~",

#
glo

glo)

~",

glo)

I:

glo

glo

glo

lO

25
25

. , ,
:

1.

( ).

2.

3.

(J , I . .).

i i,

i ,
:

212

= 5

fuc

lamda:

m,

/.

Python 3

11

#
#

prit(fuc())

n, r

n, n

11.27.

;"'"""'""''""'"""'""'"'''""'"'.'''.'"'"'''".'.''.'.<".'""'"'.''""''~'.'"'""'"''""""'".'''""'''"''''''"""'~''"'"!'""'"'""''''"'''""''""''''"''"""'""'"""""""'""'''"'"""'"'""'"""'"'"''"'"'"'"""'''"'"i

[ 17
5

fuc

(lamda

lamda:

) ()

#
#

prit(func())

n. n u
n, u.
n u n n n
. n, .
n , 11

n
~

no

n u (

11.28).

............................. , ..........., ........................, ....... , ......~.>.'''''''""'"'.''''""~""'""""""'"'.''.''"''''''"'""'"","'""'"''""''""'""'""'"'""""'"'""'''"'""'""'''"'''"'''"'""''''""''"''"""'"""'"'":

i 11.28. nr..t napaMeJ)a no


: ...... " ... '" .. ' ..................................: ................
,; ................... ......... ... ............... ; .... :... ............ ................................. '' ... ......... ...... .................... ' .......... ... :.... ' ......... ' ............... ' ..
= 5
~;

fuc

lamda

=:

=
print (func ())

#
#

n :

+
+

globals ()
locals ()

- ;

- . :

def func () :
locall = 54
glob2 = 25
prit ("

"

print(sorted(globals() .keys()))
print (" ")
print ( sorted ( locals () . keys () ) )
glo, glob2 = 10,
fuc 1)
pr it (" " 1
prit(sorted(globals() .keys() ))

11.

213

['

uiltins

package

['g1ob2',

',

cached
'func', 'glo',

doc
'glob2']

file

file

name

'locall']

['

builtins
_package ',

cached
'func', 'glo',

vars ( [<> J )

doc
'glob2']

. ,
.

<>._dict ___j. :

def func():
locall = 54
glob2 = 25
print (" ")
print(sorted(vars() .keys()))
glo, glob2 = 10, 88
func()
print 1" ")
print(sorted(vars() .keys()))
prit ("

")

print(sorted(vars(dict) .keys()))
rint("

print(sorted(dict.

11.1 .

")

dict

.keys()))

,
.

n -.
n (

11.29).

l. .~.~~~.~~. ~.~.~.~!.: . ~.~~~~.~~~.~~. !~.~~~n~u.,:.


def funcl () :
def func2():
print(x)
return func2
fl = func1(10)
f2 = func1(99)
fl 11
f2 ( 1

#
#

10
99

214

/.

Python 3

func1

1), .
1) func2 1). func1 1)
. func2 1) fi
, func1 1). ,
func1

, 6!/0.)/Ci!IIIII

: .
, -,
.

func1

1).

, ,

. , func2

1)

l , :

def func1

()

def func2():
print(x)

= 30

return func2
fl

func1 (10)

f2

funcl (99)

fl 1)

#
#

f2 1)

30

30

. 30.

, :

def func1

():

def func2 (=) :.

print(x)

30

return func2
fl

func1 (10)

f2

func1 199)

#
#

fl 1)
1)

10

99

, funcl ( 1.
func2

1).

func2

11

. .

func2

1) .

func1

1).

, n

- .
n, Pytln
.. . ...... ' ........... ' ...... ' .. ".......

non1ocal (

11.30).

. .... 1' .. '' ... '' ...... ,. . . . ..... ''. 1.'.' .......... ,. '"' ... ' .... 1' .. '" ... ' ....... , ' ..... "' ... '' ... , ' ... ' 1. '.: .. '' '. .. "."' .. " ... ' .. '' ... '" ... ' .... '

~ 11.30.

~:

nonlodai

............. .................. ............................... ;...............................................~..... ....... ;.................. '' .................... :........................ ,.. :... ,.. , ....................... ,,,, ..
',,.,

def funcl

():

11.

215

def func2 () :
non1oca1
print(x)
=

non1oca1

func1()

return func2
f = func1 (10)
#
lt
#

f (5)

f(12)
f(3)

:
:

10
5
12
non1oca1 ,

-.
.

11.11.

Python 3

,
. :

def

< >(
[<1>[:

<>]

[=<

<N>[:

<~>]

[=<

) ->

<

no
no

>][,

>]]]

>:

< >

<~> <

Python.

>

def func(a:
print(a,

"1",

10 + 5 = 3) -> None:

"1 ".

10 + 5, 3 - .

(None).

_annotations_

>>> def func(a:


>>> func.
{'':

"1",

10 + 5 = 3) -> None: pass

annotations

'1',

'':

15, 'return': None}

12

r). Pytln .
, , ,
. ,

Python.

, .
, ,

"_main_". _name_.
_name_

"_main_",

- . :

print(

name

ma1n

, .

12.1 .

.......................... ""'''"'''"'''"''""'""'"''''"'''"'''"''"''"""'"''"'"'"""""""'"''"''""'''"''"''""''"'''"'''"''"''''"''""'""''""'"''""''".. """""'""""'""'"'""'""'''"''''" ...................... ,

12.1.

n n

if

name
main "
print (" n")
else:
print 1" " 1

12.1.

import

import.

. , time

strftime

import time
print (time. strftime ('"isd. '~m.

%"))

#
#

1):

time

import :

import

<
<

1> [as
N> [as

<
<

l>] [,
N>]]

import . ,

. -

12.

217

1 ~, . 1
,

. , ,

,
.

, < .
1

time

math

12.2).

12.2. n

import time, math

prtltime.strftimel'"hd.%m.~Y"II

pnt

lmath.pi)

pi

,
, .
. ,

pi,

math,

math.pi

getattr 11

n , 1

.
11 n . :
getattri<Oe >,

<>[,

<

>])

AttributeError.

, ,

, .

12.3.

. . . . . .:: : : : : : : : : .. .

["~~~i~~~::~:~:.:.:~:~~:~~:~.:~~~~~~~~~~~-~i~~~~.~-~~t~<>..
import math
print lgetattrlmath, "pi"l 1
print lgetattr lmath, "", 50) 1

pi
50,

hasattr 1<>, <


True.

>). , 1
n

12.4.

math

12.4).

import math
def hasattr_mathlattr):

if hasattrlmath, attr):
return " "
else:
return " "
print lhasattr _math 1"pi") 1
#
print lhasattr_math 1"" 11
#

218

/.

Python 3


n , n.
n

as.

..

:ri~:;:~~~~1I$ ~ri;~~~~~~ri~~~~~~~~;::-",.

math

#
#

n n

m.

math

12.5).

.. ,.. . . . . . :-::. . . . :. . . . . . ,. . . . . . . .: - . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .:

;, : .~ .......... :;; : ... ;, : .. '.; : .... ::; : :; : . :,.,. : .....=: ~ 1: ;~;;.: .:-;.:..... ;;;;.:;i::. ' ... ~- .. :....... ;. . ;.:: .::..... ;:.......... ;, .. ::;, :..::;,. ~;. ::. '' .. ;.'.......... ' ..... '..... ;,

import math as m
print (m.pi)

........... :...... ' .. ;, .' .............................. .

pi

math

n .

n n
,

import. , n

n . n
n n . n n

n n (

tests.py,

~~;;~~~

.. :..

~~--:

-*-

. 1'2:&;.

~~;~~~;:~~;~~~;:~~:

........................... .... ; ..
~

:.~

.... ;......... ... ... ...


~;

~:

;:,,.;.;;,

12.6).

. . . . . . . . . . . . . . . ,. . . . . .,. . . . . . . . . . . . . . . . . ,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . , :

.... .................... ...................................... :..............


:~

;.,,.,;:.~

....................................................................:....................... ;

coding: utf-8 -*-

50

n n n , . n

tests.py

............................. ;.,............. ;,;,,,;;:.. ......


;;;

n (

;.

.. ....................................... ................ ...


;;;,,;;,

# -*- coding: utf-8 -*import tests


#

12.7).

............. ;,,,;,,,,,,,,,,,..,,,.,.,,,;,,,,;,,,,,,,,,,,,..........................................................................

; :,,,;,;,,.,,;

tests.py

22

print (tests.x)
print(x)
input ()

#
#

n, n n n
. ,
, . . n n n .

n n n
nn

_pycache_

tests.py.
tests.cpython-32.pyc.

n - . -

. n n

tests.cpython-32.pyc.

tests.py

, n

. n n

testsl.py),

n n

tests.py (n.
tests.cpython-32.pyc nn _pycache_ n
tests.pyc, n n.

n. ,
, n n , .

12.

219

pycache

Python 3.2.

, . ,

tests.py,

tests.pyc.

, .

from).
modules

sys.

import

import (

. n

. n
n (

modules,

12.8).

ii~~~,~~"1i'8'~''8~'~;;;;~~~''riri~~~;"~~~"'o""'''"'"'""''""''"""""''""'""'"''''''"'"""""""'"""""""'""'"""""'""" """"""""'""""'!
.......................................................................... :::.. :: ..;,: ......................................... ;............................... :........;,,;,,,, .......... ~ ................................................................... .

;,,,,,,,,,,,,,,.,,,

# -*- coding: utf-8 -*import tests, sys


#
printlsortedlsys.modules.keysl)))

tests

sys

putl)

import

. , n

. n ,

\1 n ,

_ import _ 1).
import 1) ( 12.9).

li....
12.9. !i!I!I~~ ....
...........:...................;..................... ;.... .... ...:.......
.. ... ;;; ....
....... . . . . ..
~

:.~

~;

i.;:.; ..... ; ..,; ... ;.;,,:,;;,;;i;.::::.~; ,;~~

~.=.~~.:

tests.py

;,;;:~ ;.;;;,,,.;;;~

....: ..............~;.; ... ::;....;.............................;.......................;.......:

# -*- coding: utf-8 -*s = "test" + "s"

m=
import
printlm.x)

#
#

ls)

tests

putl)

,
(

_ dict _,

dir 1).

12.10).

... .. """"''''''"''"''"'"'"''''"''~'."'.""''"~~-- .. >""'"'~~>".'~"""'""''""''.~'000~~~"'"''"'~'""'!~.~=~000 .. >"''"'''"''''~"!00.0"0>.":'""'""'''"'""''"''' .. ""'"'"~''"''"'''''';

:.

! 12.10. 10 n acQx t111 ..


............... ................................ ' ....................................................................... ,,.,,;,,.,, ...........:;......:. ....................:....... ................... .. " ................................................................ ''';
~

""'"'

# -*- coding: utf-8 -*import tests


printldirltests))
print(sortedltests. dict
input 1)

12.2.

.keys() ))

from

n n

220

/.

Python 3

from

<

>

1> [as < 1>]


N> [as < N>] ]
import (< 1> [as < 1>],
[ ... , < N> [as < N>] ] )
import *

import
[,

from

<

>

from

<

>

<
<

.,


. ,

floor 1)

as. pi
math. ( 12.11).
..

:~~:.~ .~:

.. ..

~:::.'.::.::..::.:.

.. .::::"''''''''''''''':''''"'''''''''':'''''''"'''''''''''''''''''::"'''''' ..............,...... ,.. .

~.~~~~~~..~-~:.~.~.:..~~~~~~~~.~--~~:....,: ....:,;...::.:...:.........;.,..;:::...:.:..:.::.;.;;:;... .,.:....,,,...."..:,,,,...,_,;,:..:.............::::....,.....,...............................................!

r...

# -*- coding: utf-8 -*from math import pi, f1oor as f


print (pi)
# f1oor 1)
print (f(5.49))
input ()

pi

,
:

from math import (pl, f1oor,


sin, cos)

from

# -*- coding: utf-8 -*from math import *


#
print (pi)
#
print(floor(5.49))
#
input i 1

math

12.12).

math

pi

floor ()

, ,
, . , ,

,
. . , , .

from

import.

12.13.

..............................................;. :.......;,,;;,::......... ;::;.:. ...... .... ;;;,:...


~

;~

# -*- coding: utf-8 -*s = " modu1e1"


module2.py

12.14.

module l.py

12.

221

................................................................ .....................................................................................................................................................
~

12.14. module2.py

# -- codlng: utf-8 -*-

module2"

"

12.15.

12.15.

# -*- codlng: utf-8 -*from modulel import *


from module2 import *
import modulel, module2
printls)
print ldulel. s)
printlmodule2.s)
input 1)

"

"

"

module2"
modulel"
module2"

, n n
. , n

s.

, n n.

module2.py. n n n n
u

import. u n .

_all_ , n
n

from module import *.


module l.py ( 12.16).

: 12.16. _all......

............................................................................................................................... ................................................................................................................................................... ;

# -*- coding: utf-8 -*, z,


s = 10, 80, 22,
all
= ["", "_s"]

""

n (

12.17).

12.17. n
........................................................

# -*- coding: utf-8 -*-

from modulel import *


printlsortedlvarsl) .keysl)))
input 1)

n n ( n ) n
:

['

builtins
~package

cached
1
,

'

1
,

'

doc

file

n, n n _s .
_all_, :

222
['

builtins
_package _' ,

''

cached
'' , ' z' J

doc

file

, n

_s

/.

Python 3

name

n , . .

n.

12.3.

n .
n , . . n n
n n. n n
:

# sys
# path

>>> import sys


>>> sys.path
n

sys. path

n n, n :

n ;

n PYTHONPATH. n

n n (

n).

n . n
n . n
n . n

"PYTHONPATH",

n n nn , n
, :

\folderl; : \folder2.

n n

, n n;

+
+

n n ;

pth, n
C:\Python32\Lib\site-packages.
n, , pth. n (

, n

) n . n

mypath.pth

C:\Python32\Lib\site-packages

C:\folderl
C:\folder2
, , n
n
n n

sys. path.

sys.path

n. n

n n . ,

C:\folderl C:\folder2
C:\folderl, . .

, n nn
n n n n n.

sys. path n n . n,
append {), n
n insert {) ( 12.18).

n n

223

12.

.........................................................................................................................................................................................,........................................................................................ ,
12.18.

loov"'''''''"'''''''''''"'''''~''"'''''' ''''''''''''''''''''''''''"'''"'''''''''''"'''''''';,,,,,,,,.,",.,,,.;,,,,.,,.,.,,,..,,,.,,,.,,,,,..,,,,.,,.,.,,.,.,,.,,.,,,,,,,.,,,,,.,,,~.,,,,,,,.,,,;,,,,,,,,,,.,,,,,,,.,,,,,,.,.,,,,,.,,,.,,,,.,,,,.,,.,,,,,.,,,.,,,,,,,,,,,,,,

-*- coding: utf-8


import sys

-*-

#
#

sys.pa~h.append(r"C:\fo1derl"!

sys .path.insert (0, r"C: \fo1der2")

print(sys.pth)

:cnput (!
n nany

C:\tolderl

~~

C:\folder2

C:\folder2

n. n,

nn C:\folde2,

C:\folder 1,

n: n .

n . u

n n. n ,
:

sys.path.append("C:\\fo1derl\\folder2\\fo1der3")

12.4.

, n n nu n.
n nu n
, . n ,

n u

re1oad (!

u:

imp.

from imp import reload


r1d(<

>)

tests.py

# -*- coding: utf-8 -*= 150

Python Shell

IDLE

n :

>
>>>
>>>
>>>

import sys
sys.path.append(r"C:\book") #
#
import tests
#
print(tests.xJ

tests.py

150

Python Shell,

800,

nn

n n:

>>>
>>> import tests
>>> print(tests.x)

800

150
n, n . n n

n u

re1oad 1)

12.19).

224

/.

Python 3

i ......................... : ....... ;,;............................ :.~ ..;:;.... ;;:,,,;;,;,.~;,:i,;,;.:.;,;~-.. ~ .j; ..,.

>>> from imp import reload


>>> reload(tests)
#
<module 'tests' from 'C:\book\tests.py'>
>>> print(tests.x)
#
800
n

reload () ,
from, n

~ n

, n
. , n

n , n n,

n .

12.5.

aenlO.'<t

_init_.py.

n ,

n n n n. n
.

n :

main.py
folderl\
init .
modulel.py
folder2\
init .
module2.py
module3 .

#
#
#
#
#
#
#
#

main.py

folderl\modulel.py

_init_.py

folderl\folder2\module2.py
folderl\folder2\module3.py

12.20.

: 12.20. ..-..init_.py

i ........................................... : .................. : .. ; ... ,; ...................... ::;.:............................................................................... :; ...=;,; ..... :................................................................................

'

# -*- coding: utf-8 -*print (" ini t


",
n
ndule

;,.;,

l.py, module2.py

...................................................................................................

# -*- coding: utf-8 -*msg =" {O}".format(

;;,,,;;,;~

module.py n

12.21.

... .......; ...;.........'..::........... ;................... ;........:.....:...-...;............................................................................ .


;

n n

main.py

n n

msg n. main.py n n
.

main.py

12.22.

12.

225

[:.::r
1:Zj2. ~~~ ~
... ...'.:....... ;...... :. :.3. .. ;.. ;;,..
. .:;;,;,:,-;,,,,;=;.;,;i;:,:;,
;~

;;~

:.';;,;;,'~: :~;

# -*- coding: utf-8 -*#n folderl\modulel.py


import folderl.modulel as ml
# BQrnee:
init
folderl
print (ml.msg)
# : folderl.modulel
from folderl import modulel as m2
print(m2.msg)
# : folderl.modulel
from folderl.modulel import msg
print (msg)
# : folderl.modulel
#n folderl\folder2\module2.py
import folderl.folder2.module2 as m
# :
ii t
folderl. folder2
prit (m3 .msg)
# m: folderl.folder2.module2
from folderl.folder2 import module2 as m4
prit(m4.msg)
# : folderl.folder2.module2
from folderl.folder2.module2 import msg
# m: folderl.folder2.module2
prit(msg)
iput

(1

n, n n n

no

. n

, n , n .
n

C:\folderl\folder2\,

n :\ :

lmport

folderl.folder2. n

n ,

import folderl.folder2.module2
n n
:
prit(folderl.folder2.module2.msg)

n .
n, n

as,

import folderl.folder2.module2 as m
print(m.msg)
n

from

n , n

. n ,
n

import:

from folderl.folder2 import module2


print(module2.msg)
n n

n, n
:

8 . 1349

import

n n

226

/.

Python 3

from folderl.folder2.module2 import msg


print(msg)
n , n

import

*:

from folderl.folder2.module2 import *


print(msg)

from

n n n.

_init_.py

_all_ n
from import *

, n n

_init_.py

folderl \folder2\:

# -- coding: utf-8 -*all


= [ "module2", "module"]
n

[ ~ 12;2. i> allam~i~y

main.py

12.23)

n .

. .

:............... :... :.. ... :........ ::... :.. ,.:; ... :...............:. :.~.:. :..... ,,,,:,;:.-.;;;,,:,; ''..;,;,;.;;:........:.;;;",;;,;,;~~;.;,;;::.;.~;- .:=;;;,;;=;;;: ..... :.. ;,;: .........................................................................................i

# -*- coding: utf-8 -*from folderl.folder2 import *


print(module2.msg)
# :
print(module.msg)
# :
input ()

n, n

folderl.folder2.module2
folderl.folder2.module3

from

. n

_all_,

from

n n

nop

, r

main.py.

n n. n

n n.

from

n . n , n
, n :

from .module import *


n , n , n
:

from .. module import *


, :

from ... module import *


, .

from

. n

import.

from . . lmport module


n n.

module3 .,

n.

12.24.

12.

227

......................................................................................................................................,............................................,.............,.....,...............................................................,...,.................... ,
f 12.24. ~ n~ module.py
:"" ...... " ... , ." ",,.,,, , , , . , , .. " ,, . , .~, .. ,, , .. ,, " .. ,, .. ,,,;"," , , ,, , ... ":,,,. ,,, "~.,, ;,,,, . .,, , ,,, ,".,,, .. ,,, . .,,, .. ;,:, ... ,;,;, '" ,; . ,.:, ". , ,; .;",, .. ~. "'""'''"',;; . .,, .. ,;;:",;;; , oi. ;,, ,.,, , ,',.,,,, ,,, , ... '", ,,.; . , "",, .. ,,,,", ... . :;,, .. ,,, ... , .. ;

# -*- coding: utf-8 -* module2.py


from . 1mport module2 as ml
varl ~ "LJ : {O}".format{ml.msgl
from .module2 import msg as m2
var2 =" : {0}".format(m21

# n modulel.py
from .. import modulel as m
'!ar3 =" : {O)".format(m.msgl
from .. modulel import msg as m4
var4 =" : {0)".format(m41
11

main.py

12.25)

.
~~~~-~;1-z:25~--~~~~~~-~;;~-~~;~~~:~v--,

. . . . . . .,. . . . . . . . . . .,. . . . . . . . . . . . . . . . . . .,. . . . . . . . . . . . . . . . . . . . . . . . . . . . !

............................................................... :............................ ,,,;,;..... :................................... .... .. .......... .................


~

# -- coding: utf-8 -*from folderl.folder2 import module as m


print (m. varl 1
# :
print{m.var21
# :
print Im. varI
# :
print (m. var4 1
# :
input ( i

~; :~

~~

............. ....... :......... :; .............; .................................................... :


~

folderl.folder2.module2
folderl.folder2.module2
folderl.modulel
folderl.modulel


Pytl11

import ,

znopm.


, .

module.py ,
:

# -*- coding: utf-8 -*import module2


# '
varl
" : {0}". format (module2 .msgl
r2 = var ~ var4 =

n
n n
n

folderl\folder2\.

module2.py module.py.
mai11.py (. 12.25).
n, n module2.py

n ,
, n.

n , ,
n

from:

from . 1mport module2


n n:

import folderl.folder2.module2 as module2

13

- ()- u
, . u
,
, .
"" . - ,
u .

ampu-

ymawu, u- . , . .
, .

13.1.

class

<

["""

>

[ ( <naccl> [,

J!I'-1

<

... ,

class :

<naccN>])]:

"""]

>

u ,
class. ,
.
1 .
, . .
u class ,
. ,

13.1 ).

13.1. onpeerielltfl IJ

# -*- coding: utf-8 -*class MyClass:


"""

print
ir.put ()

("

")

13.

229

yclass .

print (),

class, ,

() .
, ,

def.

self,

self

. , :

self ..

. .
:
<

>

= < >

MyClass

( [ <Il>] )

print_x(),

, (

class MyClass:
def
init (self):
self.x = 10
def print_x(self):
print(self.x)
= MyClass ()
c.print_x()
print(c.x)

13.2).

#
#
# self - m
#
#
# print_x ()
# self
#

:
< >. < >

( [ <Il>] )

,
, .
.

:
<

>.<

>

getattr () -

, .


. :
getattr(<Oe>,

<>[,

<

>])

AttributeError.

,
, ;

setattr () -

. .

:
setattr(<Oe>,

<>,

<>)

230

delattr

(<>,

1.

Python 3

<>) - .

hasattr (<>, <>) -

True.

class MyClass:
def
init (self) :
self . = 10
def get x(se1f):
return self.x
= MyC1ass ()
print(getattr(c, ""))
print(getattr(c, "get_x") ())
print (getattr (, "", 0))
setattr (, "", 20)
printlgetattrlc, "", 0))
delattr (, "")
print(getattr(c, "", 0))
print(hasattr(c, ""))
print(hasattr(c, ""))

#
#
#
#
#
#
#
#
#

13.3).

10
10

20

True
False

(pu1ic), . .

Python

. ,
. , .

class MyClass:
pass
MyClass.x = 50
1, 2 = MyClass(), MyC1ass()
1. = 10
2. = 20
print(c1.x, 1.)
prlnt(c2.x, 2.)

13.4).

#
#
#
#
#
#

50 10
50 20

pass.

().
. ().

.
(, ), . ,
,

struct

. , -

13.

231

.
.
~ .

. () ():

class MyClass:
= 10
def
init
self.y

(self):
20

cl

MyClass ()
MyClass ()

#
#

, :

print(cl.x, 2.)
MyClass.x = 88
print(cl.x, 2.)

# 10 10
#
# 88 88

, "
. :

print(cl.y,
cl.y = 88
print(cl.y,

# 20 20
#
# 88 20

2.)

2.)

cl.

,
.
:

MyClass.x

88

cl.x

= 200

,
. , :

print(cl.x, MyClass.x)

13.2.

# 200 88

_init_. () _del_()

_init_ ().

. :

def

init

rself[,

<!>[,

... ,

<N>]]):

<>

_ init _ ()


:
<n >

< >([<l>[,

... ,

<N>]])

232
eoa_init_()

/.

Python 3

13.5.

~ii~~~1:;;5~~91':.:~h~~.<>::::;'~,;,.7;::,:.::;:;:::::::...:..l
:

............................................

;,,,;,,;,,;;

.......... ............. ..................... ............,........ ;;,.;.,........:............ ............ ......................................... ...................................................... ;,, ................................ :
;

;;

class MyClass:
def
init (self, valuel, value2): #
self.x = valuel
self.y = value2
#
= MyClass(lOO, 300)
print(c.x, .)
#

100 300

,
, .
_del_ () (

Python
13.6). ,

, .

, . . , n

ii~r 1:&.

Python

. . LP >

: , ,.,,,,,.,,,,:;, ....... ;,;,;,,,,;;,, ..... < ;,;;;,:,,,.;;;..............~.~.:;;;;,.;;>,:;.::;,,.:,;;,,;~;;,,; ..

class MyClass:
def
init

(self) : #

rint("

def

del

(self):

rint("

cl = MyClass ()
del cl
2 = MyClass ()
= 2
del 2
del

13.3.

#
#
#
#
#
#

init

()")

del

()")

init
del
init

n
.

()
()

()

del

()

, , . ,
(,

Class2),

Classl).

u (

13. 7).

class Classl:
#
def funcl(self):
print (" funcl () Classl")
def func2(self):
print (" func2 () Classl")
class Class2(Classl): # Class2 Classl
def func(self):
print (" func () Class2")

Classl,

13.

= Class2 ()
funcl ()
. func2 1)

#:

#:

. func 1)

233

Class2
Classl
Classl
Class2

funcl()
func2()
func3()

Classl
Class2. , Class2 Classl.
Classl .w ., Class2 u

II. . .

Class2 Classl.
Class2. ,

. .
.
(

13.8).

class Classl:
#
def
init (self):
print (" ")
def funcl (self):
print 1" funcl () Classl")
class Class2(Classl):
# Class2 Classl
def
1n
lself):
print (" n ")
Classl. init (self) #
def funcl(self):
print (" funcl () Class2")
Classl.funcl(self)
#

Class2 ()
funcl 1)

#
#

Class2

funcl ()

funcl()
funcl()

Class2
Classl

!
,
.

super

superi[<acc>,

(). :
<

Classl.

init

super ()

(self)

self>])

234

/.

Python 3

super().

init

()

super(Class2, self).

init

() #

self

super ()

. ,

super ()

, . ~1
.
.

Python 2

n : ""

Pythqn 3

obj ect.
obj ect.
obJect,

n . "" ( n

Python 2)

13.4.

Python 3

n.


. .
(

13.9).

~ 13.9. Q~ n

:.................................. :........................................ :.......................;,,,.,;,,,,,,....... ; ...................... ;, .. ;,,;;,,;...... ,;...............................................................................

class Classl:
# m Class2
def funcl(self):
print (" funcl () Classl")
class Class2(Classl): # Class2
def func2(self):
pri nt (" func2 () Class2")

Classl

class Class(Classl): # Class


def funcl(self):
print("Meo funcl () Class")
def func2 (self):
print("Meo func2 () Class")
def func(self):
print (" func 1) Class")
def func4 (self) :
print (" func4 () Class")

Classl

class Class4(Class2, Class): #


def func4 (self):
print (" func4 () Class4")

Class4 1)
funcl 1)
. func2 1)
. func 1)
c.func41)

#
#
#
#
#

235

13.

funcl 1)

n
:

funcl 1)
func2 1)
func 1)
func4 1)

Class4

Class

Class2

Class

Class4

Classl Class.
funcl 1) Class,

Classl.
func2 1)

Class2

Class.

Class2

, .
Class, .

Class (

Class4

func2 1)

13.1 0).

:'"''~''''""'''"'"'~'""'""'""'''"''~'"'""''~"'""'"'"""'""'"~'"'~'"''"'""''""'""'"''''~"'!~."'"~'."'"'""'.''.'''''''"""'"""'""00"0""''''"''~"'""'''""'''~''"'''<0"00"0""'""'"'"'''"''"'"'""'""'"'''''''~

~.~f..~:~~,..~. ~...:~~.:.~~~.~-~~!..~:~::~.~~.:~.~.~~~~~,~.~.~~.~!f~~:.i. . ,. :.;, .,. . :.: : :. :.:. . . . . . . . . . . . .:.,.............:, . . . ''' . . ..


class Class41Class2, Class3): #
# func2() Class, Class2
func2 = Class3.func2
def f~nc4(self):
print 1" func4 () Class4")
func
.

1) Class,
func4 (), Class, .

,
.
,

_ bases _. .
:

print(Classl.
print(Class2.
print(Class.

print(Class4.

bases
bases
bases
bases

(<class
(<class
(<class
(<class

'object'>,)
' main .Classl'>,)
' main .Classl'>,)
' main .Class2'>, <class '

main

.Class'>)

13.1 1).
~~;~~~._,

....... :............... :.

:: ...;,,;,;,:................. ;;,; .....~ .... ;:...... :.:

.;,-.;,,,',;

class Classl: = 10
class Class2(Classl): pass
class Class3(Class2): pass

... ;, ..;:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .!

........ ;;:. :. :..:; .....

~~;';;; ,,,; ;~',:;; ;;~';. ;:

;.:::;~

.. :; .................. ; .............. ;

236

/.

Python 3

class Class4(Class3): pass


class Class5(Class2): pass
class Class(Class5): pass
class Class7(Class4, Class): pass
= Class7 ()
print(c.x)
:

Class7 -> Class4 ->

Class

- >

Class

-> ClassS -> Class2 -> Classl

_mro_:

mro

print(Class7.

(<class
<class
<class
<class

13.5.

1
1
1
1

main
main
main
main

.Class7 1 >,
.Class3 1 >,
.Class5 1 >,
.Classl 1 >,

<class 1 main .Class4 1 >,


<class 1 main .Class6 1 >,
<class '1 main .Class2 1 >,
<class 1 0bject 1 >)

+ _ call_ ()

call

(self[,

<l>[,

... ,

<N>]])

class MyClass:
def
init (self, m)
self.msg = m
def
call (self) :
print(self.msg)
cl = MyClass ( "l")
2
MyClass ( "2")
cl ()
2 ()

setitem

#
#
#
#

n
:

(self, <>, <>) -

_getitem_(self, <>)-
. for,
, . :

class MyClass:
def
init (self, ) :
self.arr =
def _getitem_(self, index):
return self.arr[index]

13.

237

def

setitem (se1f, index, va1ue):


.se1f.arr[index] = va1ue
= MyC1ass ( [ 1, 2, 3, 4, 5 J )
# : 1
print ( [0])
#
c[OJ =
# :
print(c[OJ)
# for ffi __getitem__ ()
for i in :
print (i, end=" ")
# ffi: 2 3 4 5
print (1ist ())
# : [0, 2, 3, 4, 5]
print("Ec" if in e1se "") #:

de1item

(se1f,

<n>)--

de1

< > [ <n> J;

__getattr__ (self, <>):._


. :

c1ass MyC1ass:
def . init (se1f) :.
self. i = 20
def __getattr__ (se1f, attr):
rint(" __getattr__ ()")
return
= MyC1ass ()
# i
print(c.i)
# : 20. __getattr__ ()
# s
print(c.s)
#: __getattr__ ()

__getattribute__ (self,

ffi

<>)--

. , (
) .
,

__getattribute__ ()

object.
AttributeError. :

c1ass MyC1ass:
def
init (se1f):
self.i = 20
def __getattribute__ (se1f, attr):
rint(" __getattribute__ ()")
return object. __getattribute__ (se1f, attr) # !!!
= MyC1ass ()
print(c.i)
# ffi: __getattribute__ () 20

__ setattr__ (se1f,

<>,

<>)--

.
,

__setattr__ ()

__dict__,

, . :

c1ass MyC1ass:
def
setattr (se1f, attr, va1ue) :.
print ("
setattr () ")
se1f. dict [attr] = va1ue

!!

238
= MyC1ass ( )
c.i = 10
print(c.i)

#
#

10

setattr

_de1attr_(self, <>)-
de1 < >. <>;

_iter_(self)

Python 3

()

n n

n, . n

n.

_geti tem_ (),

/.

nn _ i ter _

n _next _

(),

().

_iter_ ()

_ i ter _

()

. _next_() "

Stopiteration,

. :

c1ass MyC1ass:
def
init (se1f, ):
se1f.arr =
se1f.i = #
def
iter (se1f):
return se1f
def
next (se1f) :
if self.i >= 1en(se1f.arr):
se1f.i =
# .
raise Stopiteration
#
e1se:
elem = se1f.arr[se1f.i]
self.i += 1
#
return e1em
= MyC1ass ( [1, 2, 3, 4, 5] )
for 1 in :
print(i, end=" ")
# : 1 2 3 4 5
pr1nt(c. next ())
# : 1
pnt (.
# : 2
next ())
for i in :
print(i, end=" ")
# : 3 4 5

_1en_(self)- n n 1en(), n
n _ 1_ ().
n . :

c1ass MyC1ass:
def
1en (se1f) :
return 50
= MyC1ass ()
print (1en ())

+
+

50

_1_ (self) - n 1

int

(self) int ();

();

n n

float

(self) -

float ();

13.

239

+ _ complex_ (self) - n n complex ();


+ _round_ (self, n) - n n round();
+ _index_ (self) - n n n (), hex () oct ();
+ _repr_(self) _str_(self)- n .
_ repr_ ()

print (),

n , n n

repr().

_str_()

n n

n n

_repr_().

str ().

_str_ ()
_repr_()

str

()

. :

class MyClass:
init (self, m) :
def
self.msg = m
repr_(self):
def
return " _repr_() {O}".format(self.msg)
def str (self) :
return " str () {O}".format(self.msg)
= MyClass ("")
print(repr(c)) # m: _repr_()
print (str ()) # m: str (")
print ()
# :
str ()

+ _hash_(self)-

n, n n

n . :

class MyClass:
init (self, ):
def
self.x =
def hash (self):
return hash(self.x)
= MyClass(lO)
d = {}

d[c] = ""
print(d[c]) #:

13.6.

n n n n.
n n, n n
. n n n :

+ + --. add ();


+ + - (n n)- x._radd_(y);
+ += - n- x~_iadd_ ();
+ ---. su ();
+ - -(nn)-._rsu_();
+ -= - n- x._isu_(y);
+ * --._mul_();

240

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

Python 3

- ( )- x._nul_ ();

*=

1 --.

- - . _

truediv

imul_ ();

();

1 - ( )-

x._rtruediv_ ();

/=- -._itrudiv_();

11

. _

11 - ( )- . _ rfloordi v _();

1 1=

f loordi v_

- -

% - -.

x._ifloordiv_(y);

();

mod

- -

%=

()

( )

. _ nod_

- -

- ( )-

.""*=

+- + ()-

abs () -

x._rpow_ ();

x._ipow_ ();

x._neg_();

x._pos_ ();

- .

abs

().

13.12.

: .,r 13.12.
class MyClass:
def
init (self, ):
self.x=y
def
add (self, ):
# +
print (" ")
return self.x +
def
radd (self, ) :
# +
print (" ")
return self.x +
def
iadd (self, ):
# +=
print (" ")
self.x +=
return self
= MyClass(50)
print(c + 10)
# : 60
print(20 + )
# : 70
+= 30
# :
print(c.x)
# : 80
:
-- -._ invert _
& --.

and

x._pow_(y);

- -

-- - ()-

()

x._imod_(y);

+
+

/.

();

();

13.

241

& -(nn)-._rnd_();

&=

~ - - .

- (n n)-

- - .

- (n n)-

- n-

+
+

- n (n )- . _

--._ind_();

--.

or

();

- (n n)- . _

1=

- -

ror_

x._ior_ ();
xor

();

- n- . _

lshift

();

x._rxor_ IYI;

ixor _ IYI:

1yl;

- n-

x._rlshift_(yl;

x._ilshift_ ();

x._rshift_(y);
rrshift _ 1yl;

-nn-._irshift_().

n n :

+
+
+
+
+
+
+

==

--._q_();

!=

--._n_();

<

--.

>

y-owe-x._gt_(yl;

<=

-.-._l_();

>=

- -

in

- n - . _

lt

(yJ;

x._ge_(y);
contains_().

n n n

13.13.

class MyClass:
def
init (self):
self . = 50
self .arr = [1, 2, 3, 4, 5]
def _eq_(self, ):
#
return self.x ==
def
contains (self, ):
# in
return in self.arr
= MyClass ()
print("Pao" if
50 else " ") # :
print("Pao" if
51 else " ") #:
print ("" if 5 in else "")
# :

242

13.7.

/.

Python 3

,
.

@staticmethod.
:
<

>.<

>(<>)

, :
<

>.<

>(<>)


:'"""""' "'.' '" "" '" "'"~."'" >,.' "'"""'.''~' ~'' "~ ".~' ~~'"~' ""

"N.' ''<,"~'""-'~~~~~'.' '~"~~~.' ~ .. ~~~ ...... "~" ~" "" "" "" ~ 000~ " '~" ""'""' " "' ' ' " "" ._''" ' " ""'""

~ 13;.14, G~~ ~r1


:........... ;...................... :...... ;; .... :;:........... ;.. :.... :;,;~ .. ;.;;,;;;,;;,;,;;,;;;,;:;... ~;.;.. ;.~ ....... :;,;,;,;;,.;;,~--.... ;;;;,;,;;;'.~;;.;;;;;;;,.;;;;,;',,;;;,'.. ;,...... ; .............

class MyClass:
@staticmethod
def funcl(x, ):
return +
def func2(self, , ):
return +
def func(self, , ):
return MyClass.funcl(x,
print(MyClass.funcl(lO, 20))
= MyClass ( 1
print(c.func2(15, 6))
print(c.funcl(SO, 12) 1
print(c.func3123, 5))

13.14.

".

#
#
#
#
#

................. :........ :.......................................................:'

' "" ' "

, self.
,
.

@classmethod.
, .

:
<

>.< >(<>)

, :
<

>.<

>(<>)

13.15 .

~ : " .' ' ' ''.: ~.' '' .'.' ;. : 1' ''' . ' ' . " " '." , , . . . . : .'.'.' ' . . . . . . . . . . . . . ' ' , '' , . ' . . . . . . . . . . . , ' , ' ' " . . . . . ' ' . ' . . . . . . . . . . . . . '.. , ....

.' ' 1 ' ' . . . . . . . . ' ' ' "

!:.~~~~~.~.~. ~.~:.~~~.:. ~~~~~~.~:.~~:~,~~ . .~,. . ..,.:~...::.::....:..:.. :.~...}.:... :.:...:: ...:.:..:.:....:.:,,... ....... .....................................................................!
class MyClass:
@classmethod
def func(cls, ):
print(cls, )

MyClass.func(lO)
~ MyClass ()
c.func(50)

13.8.

243

13.

u. .

- u.
.
(

13.1 6).

' ....................... , , ..... '"'' .................................................. '"' ' ............... ........... ' , ''"". ! s
.; ''" ....... '".' ........ ' ......... " .......... ..' .......... ' .................
. " ......... ' .......
. , ..........................
.
.. ..
.
.
.
...
:
[ .13.16. i
;
..:; .................................................. :~.:.:~ ....................... ~ .............:......... :... ;;,;,,., .. ;:......... ;,; ... ;......................................... ;,...;.\....;.... J
~

-~

'

:.................,.............. .....................................
class Classl:
def func(self,

):

n raise
raise NotimplementedError (" nn
~

class Class2(Classl):
def func(self, ):
print(x)

")

class Class3(Classl):
pass
~ Class2 ()
c2.func(50)
~ Class ()
try:
c3.func(50)
except NotimplementedError
print (msg)

nn

Python 2.6,

50

# m
# . func() nn
as msg:
# : nn
.

@abstractmethod,

, ,

, .
-, ,

TypeError.

@abstractmethod

13.17).

t.-.. ................. " .. ;............... ,,;,;;; ;,,;;.................. ;.~;.;:;.... .

from import t, abstractmethod


class Classl(metaclass=ACMeta):
@abstractmethod
def func(self, ):
#
pass
class Class2 (Classl) :
def func(self, ):
print(x)

#
#

244
class Class3(Classl):
pass
2 = Class2 ()
c2.func(50)
try:
3 = Class3 ()
c3.func(50)
except TypeError as msg:
print(msg)

13.9.

/.

Python 3

50

func()

# Can 1 t instantiate abstract class Class3


# with abstract methods func

Python

, . .

_getattr_(), _getattribute_()

_setattr_(),

. ,
, .
.w. ,
.
, ,

. ,

_privateVar Classl

_Classl_pri vateVar.

.
r (

13 .18).

~~~-~:;:1:~;~~~;~~--~;~~~~~"~-

. . ". . ",.,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ,

.................. ..................... ............................................................. ................... :.............. ;........................ :...............................................................

: ....................... ; ..........................

c._MyClass_privateVar
print(c.get_var())

50

;;,

class MyClass:
def
init (self, ):
self. _privateVar =
def set _var (self, ):
self. - privateVar =
def get - var (self):
return self._privateVar
= MyClass(lO)
print(c.get var())
c.set_var(20)
print(c.get_var())
try:
print(c._privateVar)
except AttributeError as msg:
print(msg)

#
#
#
#
#
#

10

20

I1

I1 1

# : 1 MyClass 1 obj ect has


# no attribute 1 _privateVar 1
# ~
#
# : 50

13.

245

, .

_slots_.


. ,


:~:''

_slots_,

AttributeError ( 13.19).

: ' '. : . , . ' . '' ::" , ''."!' ': '''''.':.< ~-.. .:.:.

t r 13.19. . $iib.

;, .....................~ ........................... ~:...........,; ...~.:.:.:~;i;t~j;,.;.;,,;~ .. ;,;~'.

class MyClass:
= ["", ""]
slots
def
init (self, , ):
self.x, self.y =,
= MyClass(l, 2)
print(c.x, .)
., . = 10, 20
print(c.x, .)
try:
c.z = 50
except AttributeError as msg:
print(msg)

13.10.

#
#
#
#
#
#

1 2

10 20

slots

# 'MyClass' object has no attribute 'z'

,
, .


<>

rrt(<>[,

[,

<>[,

property ( 1. :

<>

< >]]])

, .
,

. ,
. -

None,

, .

13.20).

class MyClass:
def
init (self, value):
self. var = value
def get_var(self):
#
return self. var
def set_var(self, va1ue): #
self. var = value
def del_var(self):
#
del self. var
v = property(get_var, set_var, del_var,

" ")

246
= MyClass(5)
c.v = 35
print(c.v)
del c.v

#
#
#

Python 2.6

/.

Python 3

set_var()
get _ var ()
del_var()

getter (), setter ()

deleter (),

13.21.

. . . .,. . . . , :, . .,.,. .,., . . ,. . . . , . , . ., . ., . . 1

i~~~~~~,;:2-1~i,i~~t~-(j:;~~~tt'~~~~-t1::::,:,:.,., ~:::;;.:,:,., ,~,,,


:

........................................:..........................;;,,,,,.;,, ..:. ................ ..............;, ............... ,,,;;;.,,,,.,,;,................. ,,.;;.,, ...... ._ .. ,; ........... ..................................
:

class MyClass:
def
init (self, value):
self. var = value
@property
def v(self):
return self. var
@v.setter
def v(self, value):
self. var = value
@v.deleter
def v(self):
del self. var
= MyClass(5)
c.v = 35
print(c.v)
del c.v

13.11.

#
#
#

~..............

....................... ..................

Pytho

, .

, ,
- .

13.22.

:"'"''''''''''"'"~'''<'''''''''""''"''.''.~''"'''""'""".'" ... >"'"'''".'.''""'"0.'_'.'''~''.'.''~''.".!.'"~''"".'~''''".'':'.''''0~.'.':'.~'.'"'"'"'"'"""'.~'"'''"'~~.'~'~''.''''~''''~''~.""'""'""'""''"'''"''''''''"'"'""'''""'''"'"'~'''"'''"'"j

\. .~.~~~-~... ~.~:.~.f:P~.~.?P~~g~~!:.~~-~8~~,;_.:,,::::::::::.::.:::. . . ,. . . .::::.:~:::.:,.:.:.:. ::.::::o:i,..:::::::.:::::.::c::;:.:.... ;;.::........:.......;;.......................:........................... .i


def deco

()

print("Byp ")

return

@deco
class MyClass:
def
init (self, value):
self.v = value
= MyClass(5)
print(c.v)

#
#
#

14

- .
,
.
:

- ,
. ., . . . ,

,
. :

>>> print("He : !)
SyntaxError: EOL while scanning string literal

- ,

. ,

. , . . .
;

- ,
. , .
:

>>> def test(x,

):

return

>>> test (4, 2)


#
2.0
>>> test (4, 0)
#
Traceback (most recent call last):
File "<pyshell#4>", line 1' in <module>
test(4, 0)
#
File "<pyshell#2>", line 1' in test
def test(x, ): return 1
ZeroDivisionError: division zero
, Pytho ,
- . ,

ValueError, :

index ()

248

/.

Python 3

>>> "". index ("")


Traceback (most recent call last):
F'ile "<pyshell#5>", line 1, in <module>
"". index ("")
ValueError: substring not found

14.1.

try... except... e/se... finally

try. :

try:
<,

[e>:cept [ <1> [ as
<,

>

< >]

]:

>

...

except

[<N>[

<,

as

<

>]]:

>]]

[e1se:
<,

m,

>]

[finally:
<,

>]

, ,

try. except <1>


. , , ,
,

14.1.

~~~i.~~~::~~~:1.~::~~~~~~~~~~~~~~-:~~:~i.~~::::::::::::.:::::::::::::;:::::::::::::::::::::::::::::::::~:::::::::::::~::::::::::::::,:::::.::::::::.::::::::. ::::::::::::.::.:::::_:::J
try:
= 1 1
except ZeroDivisionError:
print ("

#
#
#

=
prlnt(x)

")

try , except. ,
,

except. except ,
"" .
, ,
.

, except
. , (

14.2. -rt

14.2).

....................................................,;... :....'..... ;.,,;:,;.:....:.... ; ...... :........ :...... :.................. ;....;:.. :..;;;'.', ................. :., ........... :..... :..................................................................... .

try:
try:

= 1 1

#
#
#

14.

except NameError:
print 1"n
except IndexError:
print 1"!1
printi"Bpaee

249

")

")

")

except ZeroDivisionError:
print 1"
=
printlx)

")

ZeroDi visionError, n
1 "" .
, .
,

(print lx) ). , print 1" n

") .

except

( 14.3).
' 14.3. Q
:

......................................................... .............. ;... :........................................................::................... .......................................................;................. .. ........................................ .


;,;~

try:
= 1 1
except INameError, IndexError, ZeroDivisionError):
#

printlx) #

except

14.4).

i .................................................; .................. ;,, ......................;~; ;.:,.;,, ; ..................~.; ~..........; ............. ~; ........................ ; .................. " ......... ~ .............. ," .................. ~ ........................... ;

try:
#
= 1 1
except INameError, IndexError, ZeroDivisionError) as err:
printlerr. class ____ name
#
printlerr)
#
:

ZeroDivisionError
divlslon zero
~ info 1)

sys,

: ,

traceback

traceback.

14.5.

exc~info

1)

250

/.

Python 3

import sys, traceback


try:
= l 1
except ZeroDivisionError:
, Value, Trace = sys.exc_info()
printi"Type: ", )
print("Value:", Value)
print("Trace:", Trace)
print ("\n", "print_exception() ".center(40, "-"))
traceback.print_exception(Type, Value, Trace, limit=5,
file=sys.stdout)
print("\n", "print_tb()".center(40, "-"))
traceback.print_tb(Trace, limit=l, file=sys.stdout)
print("\n", "format_exception()".center(40, "-"))
print(traceback.format_exception(Type, Value, Trace, limit=5))
print ( "\n", "format _ exception_ only () ". center (40, "-") )
print(traceback.format_exception_only(Type, Value))

14.6.

~~.l~o.II,>~>!"'~'''"''"'"'''"""'''""''"''00"''"'~0>":~.'"~."":'''"''!~'.''":"'"'~'~''000"''""'~''""''.''M0.'!"'!''''~~~='''~~.'!.'""''"'''''""'''''.'!'!'"'~'00"'!'"'"'''"'.".'''""""''"'''"''''''"'"''"'"'''''''''"""''''"''""'.'''''"'"''1,

[1114;ir 14,5: P!tyn~ra t..in<JnJ-I(tJ-IfJ .nr

14(fi . .. . . . .. .

..

:. :~~.;~~:: .-.~~--.....:;,;;,,,;,,;.......... ~;.:.:;, .. ,,,,.;;; ....;; ..~:;;;;,~j;;~:;,,;:,:;;;;~:;;;;~;.,,;.,.,;,;;;;~;~'.;;;;;";,: ....... ;....~; ....;;.. ~ . ~;;;,:;;;;,.,.;,.;,;,,;';;;,;,;=;,;,;.~=..:,.;,; .. ;... ,. ;...... .:: ... :.............................. .- ..:... :........... :...... :................:;
:
<class 'ZeroDivisionError'>
Value: division zero
Trace: <traceback object at 0030>

-----------prlnt_exception()-----------Traceback (most recent call last):


File "C:\book\test.py", line 3, in <module>
=

ZeroDivisionError: division

zero

---------------print tb()--------------File "C:\book\test.py", line 3, in <module>


= l 1
-----------format exceptlon()----------[ 'Traceback (most recent call last) : \n', '
line 3, in <module>\n
= 1 1 0\n',
'ZeroDivisionError: division zero\n']

File

":\ \book\ \

test. ",

--------format_exception_only()--------['ZeroDivisionError: division zero\n']


except ,
.

except, . .

, , .

except

14.7.

14.

251

try:

= l 1

except:

#
#

print(x)

e1se,

n n . n -
, , n

fina11y.

n n

14.8).

try:

= 10 1 2
= 10 1
except ZeroDivisionError:
print (" 0")
e1se:
print 1" e1se")
fina11y:
print (" finally")

#
#

n n :

e1se
finally

n n :

f1nally

, n

except
finally n, . n

"n" . n
, n n

no

, n

n n . :

>>> try:
= 10 1
fina11y: print (" fina11y")

finally
Traceback (most recent 11 1ast):
Fi1e "<pyshe11#17>", 1ine 2, in <modu1e>
= 10 1
ZeroDivisionError: division zero

252
(.

4.16)

/.

Python 3

u , , .
(

# -*- coding: utf-8 -* 'stop' ")


surnma =
while True:
= input 1" : ")
= x.rstrip("\r")
# 3.2.0
if == "stop":
break
#
try:
= intlx) #
except ValueError:

14.9).

printi"Bee

(.

1.7)

printi"Heoxoo !")

else:
summa +=
print("Cya

input

:",

surnma)

1)

u :

'stop'
10
str

-5

stop

. , .

14.2.

2.6,

with ... as
Python

(, )
, .

wi th ... as. u

with

<~l>[
<~N>[
<,

as
as

<>]

[, ... ,

<>]]:
>

<~l>, ,

_ enter_ 1)

exi t

1).

14.

253

_ enter _ 1)

. , ,

n n,

as.

, . _enter _

enter

1):

(self)

n
,

with.

n n

_ exi t _ 1).

exit

(self,

<n

>,

<>,

<

traceback>)

, n n, n ,
~ info

True,

1)

sys.

False.

False,

n .
n n ,
, n
n

_exit_().

with,

None.

n n n (

14.1 0).

~'''""'"'"'''''"''''''"'''''""'"''"''"''"'"'''"'''''''''''''"'''''''''''"'''''"''' ,, .. ,,w'""''''''''"'''"''"'''"'''''-''''''''''''"'''"''"''"''''''''''"''''''''''',",,;,,,,,,,,,.,,,,,.,,,..,,~~,,,,,,,,,,,.,, ''''"'''''''''''''''''''"'''""''''''":

class 'yClass:
def
enter

(self):
enter

rint("

return self
def
exit (self,
rint("

if

()")

Value, Trace):
exit () ")

is None: #
print 1" ")
else:
#
print("Value =", Value)
return False # False ~
# True ~

rint("

with MyClass():
print ("

n :")

with")

rint("\n

:")

with MyClass() as obj:


print (" with")
raise rrr(" TypeError")
:

enter 1)
with

exit ()

254

/.

Python 3

enter ()
with

exit ()
Value = TypeError
Traceback (most recent call last):
File "C:\book\test.py", line 20, in <module>
raise TypeError (" TypeError")
TypeError: TypeError

, , .

with

open (),

.
r

with

14.11 .

~" " ' ' " " " " " " ' " ....... ' ' " . " '.' ............. " ......... " ' '' .... ' ....... !~'-'.' ... '' .... " ....... ' " ..... " . " ' ~ ' " ..... ' ........ ' ..... '! .......... ". ... " ' .......... " " ' " ' .............. ' ' . '.

t J11!:r 14.11. 11ii:wi6; ' as


.... .. .'..;;. '.. ..... '"' ...... " .'.. ': ............. .:... ... ;;.... "; ...',; ..'.";;,; :.; .. :;. ;;., .... ,;, . ;. :. ;.... ,;
~.;

-~ ;

;~~;

;;

with open("test.txt",

open ()

:. ::. ; ,,; ;;:.; :.~:. '" ,; ,;:... :;; ;, ............. ' ...... ' ..; ..........:' ... '" . ' .......... " ........... .

.. .............. 1;

encoding="utf-8") as f:

"",

f.write("Cpoa\n")

...

;-~~.;;; ' ';;~';;

' " " ' ' '." '~

test.txt

~ .

wi th.

, , .

14.3.

Pytln .

14.12.

~~"'"'''"'''''"'''"'""'.'""."('.'''("''~'"''"''~~.'"''''''''~".''~'.''.'.'~"~''.'("'""'''"'.'~~-"'""''""''"''"''"''(~''""'"""''""'"""'"'''""'"''''''"''"'"+""''"'"'"'"''"'""'""'"'''''''''''

r 14.12. 101$ ~~~(.

......... ,.,.,,,, ... ., .......... ~,.

i .. ~ .............. : ... ....~.. ;..... ;~;,;, ..........:.:....~;.;;",,,,,.: ....;;,.~;.,,;,,,, ... ;;.~ .... ;;,,;,;;;,.,; ........;.;;...............~.......: . ~; ....... ~: ........... ;;, ................... :................................................ ; .........................; ......... J

BaseException
GeneratorExit
Keyboardinterrupt
SystemExit
Exception
Stopiteration
Warning
BytesWarning, ResourceWarning,
DeprecationWarning, FutureWarning, ImportWarning,
PendingDeprecationWarning, RuntimeWarning, SyntaxWarning,
UnicodeWarning, UserWarning
Ar i trlet icError
FloatingPointError, OverflowError, ZeroDivisionError
AssertionError
AttributeError
BufferError

14.

255

EnvironmentError
IOError
OSError
WindowsError
EOFError
ImportError
LookupError
IndexError, KeyError
MemoryError
NameError
UnboundLocalError
ReferenceError
RuntimeError
NotimplementedError
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError, UnicodeEncodeError
UnicodeTranslateError
n n
n
-n.

ZeroDivisionError.

n,

ZeroDivisionError.

ArithrneticError,
FloatingPointError, OverflowError

try:
= l 1
except ArithmeticError:
print ("

#
#

")

+
+
+
+
+
+
+
+
+
+

aseException- ;

Exception- , BaseException, n n ' ;


AssertionError- assert;
AttributeError- nn i< ~;
EOFError- input () n ;
IOError- n ;
ImportError- n n;
IndentationError- n n n ;
IndexError- n;
KeyError- ;

256

+
+
+
+
+
+

/. Python 3

Keyboardlnterrupt- <Ctri>+<C>;
NameError- ;
Stoprteration- _ next _ () ;
SyntaxError- ;
TypeError -

UnoundLocalError- ;

+
+
+
+

UnicodeDecodeError- ;
UnicodeEncodeError- ;
Valt,1eError-

ZeroDivisionError-

14.4.

+
+

raise;
assert.

raise
raise
raise
raise

raise . :

<n >

< >

<n >

from

< >

raise

. .

except.

ValueError:

>>> raise ValueError("Ocae ")


Traceback (most recent call last):
File "<pyshell/10>", line 1, in <module>
raise ValueError("Ocae ")
ValueError:
:

try:
raise ValueError("Oncae ")
except ValueError as msg:
print(msg) #:
:

class MyError(Exception):
def
init (self, value) :
self.msg = value
def str (self):
return self.msg

14.

257

#
try:
raise rrr(" ")
except MyError as err:
print (err)
#
str ()
print(err.msg)
#
#
raise MyError (" ")
:

Traceback (most recent 11 1ast):


Fi1e "C:\book\test.py", 1ine 14, in <modu1e>
raise :r (" ")
MyError:

Exception .

- ,

Exception:
c1ass MyError(Exception): pass
try:
raise MyError (" ")
except MyError as err:
print (err)
# :

raise ,

. :

try:
raise Va1ueError # : raise Va1ueError()
except Va1ueError:
print (" III")

raise

, .

_cause_.


, . :

try:

=1 1

except Exception as err:


raise Va1ueError() from err
:

Traceback (most recent 11 1ast):


Fi1e "<stdin>", line 2, in <modu1e>
ZeroDivisionError: division zero
The above exception was the direct cause of the
fo11owing exception:
9 . 1349

258

1.

Python 3

Traceback (most recent call last):


File "<stdin>", line 4, in <module>
ValueError
,

ValueError,
zeroDivisionError. ,
from . from

_, :

Traceback (most recent call last):


File "<stdin>", line 2, in <module>
ZeroDivisionError: division zero
During handling of the above exception, another
exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError

raise .

class MyError(Exception): pass


try:
raise MyError ( ", !1")
except MyError as err:
print(err)
#
raise

Traceback (most recent call last) :


File "C:\book\test.py", line 5, in <module>
raise MyError (" !1")
MyError:

assert AssertionError,
False. :

assert

<

~>[,

<>]

assert :

i f _debug_

if not < ~>:


raise AssertionError(<ae>)
-,
.

assert:

try:
=

-3

assert >= , " "


except AssertionError as err:
print(err) # m: !1

_debug_
assert -.

15

- . n:
. n n n
.. , ( ) n
.

15.1.

, n

open (). :
>[, mode='r'] [, buffering=-1] [, encoding=None] [,
errors=None] [, new1ine=None] [, c1osefd=True])

n(<

n n .
. Widows ,
.
. :

>>> "C:\\temp\\new\\fi1e.txt"
'C:\\temp\\new\\fi1e.txt'
>>> r"C:\temp\new\fi1e.txt"
'C:\\temp\\new\\fi1e.txt'
> "C:\temp\new\fi1e.txt"
'C:\temp\new\x0ci1e.txt'

!!

.
:

\t, \n \f. n

:
:<>m< >w< >i1.tt

open (),

>>> open ("C:\temp\new\fi1e. txt")


Traceback (most recent 11 1ast):
Fi1e "<pyshell#>", 1ine 1, in <modu1e>
open (": \temp\new\f'i1e. txt")
IOError: [Errno 22] Inva1id aigument: 'C:\temp\new\x0ci1e.txt'

IOError:

260

1.

Python 3

.
.

os. path.

abspath ()

,
. :

>>> import os.path #


>>> # (C:\book\)
>>> os.path.abspath(r"file.txt")
'C:\\book\\file.txt'

,
. :

>>> # m C:\book\folderl\
>>> os.path.abspath(r"folderl/file.txt")
'C:\\book\\folderl\\file.txt'
>>> # m C:\book\folderl\folder2\
>>> os.path.abspath(r"folderl/folder2/file.txt")
'C:\\book\\folderl\\folder2\\file.txt'

(" .. /").

>>> # :\
>>> os.path.abspath(r" .. /file.txt")
'C:\\file.txt'

, .

. :

>>> # C:\book\folderl\
> os.path.abspath(r"/book/folderl/file.txt")
'C:\\book\\folderl\\file.txt'
>>> # m C:\book\folderl\folder2\
> os.path.abspath(r"/book/folderl/folder2/file.txt")
'C:\\book\\folderl\\folder2\\file.txt'
, .

sep
os .path. .

Windows:

>>> os.path.sep
'\\'
> os.path.abspath(r"C:/book/folderl/file.txt")
'C:\\book\\folderl\\file.txt'

, . . ,

.
, . ,
, .
.

C:\book

15.

261

C:\book\
test.py
folderl\
init .
modulel.py

C:\book\test.py

15.1.

# -*- coding: utf-8 -*import os, sys


print("%-2Ss%s" ~, (":", os.path.abspath(

file )))
os.getcwd()))
print("%-2Ss%s"% (" r! :", sys.path[O]))
print("%-2Ss%s"% (" :", os.path.abspath("file.txt")))
print ("-" * 40)
import folderl.modulel as m
m. get_cwd 1)
print("%-25s's"%

("

C:\book\folder 1\

:",

n. , n

init_.py

n .

C:\book\folder 1\module l.py

15.2 .

................ ......................................................................;,;.. ... .... .................................... .... ....... :;;,, .. ;;,,-..:,; ....; ...... ::......... ...:.... . ...
~

;;;

; ;;

,;,;;,;,,,

.............................,........................................ ;

# -*- coding: utf-8 -*import os, sys


def get_cwd():
print("%-2Ss%s" % (":", os.path.abspath( file )) )
print("%-25s%s" % (" :", os.getcwd() ))
print1"t-2Ss%s" % (" r1 :", sys.path[O]))
print("%-2Ss%s"% (" :", os.path.abspath("file.txt") ))
n , n

C:\book

test.py:

C:\>cd C:\book
C:\book>test.py
:

r! :

r!

C:\book\test.py
C:\book
C:\book
C:\book\file.txt
C:\book\folderl\modulel.py
C:\book
: \book
C:\book\file.txt

test.py.

dule l.py.

open 1) n,

C:\book,

C:\book\folderl.

262
n n : n n

/.

Python 3

test.py:

\book>cd :\
C:\>C:\book\test.py
:

C:\book\test.py

:\

C:\book
: \file. txt
C:\book\folderl\modulel.py

:
:

:\

C:\book
C:\file.txt

n , n

test.py.

test.py

modulel.py

open ()

n, n n :,
.
n n n ,
n

test.py

chdir ()

os.

15.3).

# -*- coding: utf-8 -*import os, sys


#
os.chdir(os.path.dirname(os.path.abspath( file ) ) )
print("%-25s%s"% (":",
file ))
print("%-25s%s"% (" :", os.getcwd()))
print("%-25s%s"% (" :", sys.path[O]))
print("%-25s%s"% (" :", os.path.abspath("file.txt")))
. n

n .

_file_ n n
_file_

n n . n, n

C:\book>C:\Python32\python test.py
n. n n
n , n

abspath () os .path.
dirname () n

n ( ) n

chdir (). n open () n,

n n . n
:

C:\>C:\book\test.py
:

C:\book\test.py
C:\book
C:\book
C:\book\file.txt

test.py

15.

263

, n , n

. n, ,
n , , n n .
, n n n n .
n

mode open () n :

r - ( ).
. ,

IOError;

r + - n.
. ,

IOError;

w - n. , . ,
nn. ;

w+- n. , .
, nn.

- n. , . n
. ;

+- n. , . n ~
. .

, n :

- . n
n

bytes;

t - (

n n

Windows).

str. Windows

\r , n n, , . n

file.txt

n :

>>> f = open(r"file.txt", "w"} #


>>> f. write ( "Stringl \nString2") #
15
>>> f .close ()
#

w, , ,
:, nn. n
:

>>> # ( \r )
>>> with open(r"file.txt", "rb") as f:

for line in f:
print(repr(line))
b'Stringl\r\n'
b'String2'
>>> # ~ ( \r )
>>> with open(r"file.txt", "r") as f:
for line in f:
print(repr(line))

264

/.

Python 3

'Stringl\n'
'String2'
.
.rt .

buffering . ,

( ).
1 (
), ,
( ) ,
.

( )

Unicode,

. , ;' .

encoding.

UTF-8:

>>> f = open(r"file.txt", "w", encoding="utf-8")


>>>

f.write("Cpoa")

>>> f.close()

>>> with open(r"file.txt", "r", encoding="utf-8") as f:

for line in f:
print(line)

UTF-8, UTF-16

UTF-32

Mark,

).

UTF-8

(Byte Order

, n.

UTF-8

encoding utf-8-sig.

>>> f = open(r"file.txt", "w", encoding="utf-8-sig")


>>>

f.write("Cpoa")

#n

> f. close ()

n encoding:

>>> with open(r"file.txt", "r", encoding="utf-8") as f:

for line in f:
print(repr(line))
'\ufeffCpoa'

>>> with open(r"file.txt", "r", encoding="utf-8-sig") as f:

for line in f:
print(repr(line))
''

15.

265

utf-8, n n
utf-8-sig,

n .

utf-8-sig n

UTF-8.
UTF-16

utf-16 utf-32 n encoding .

UTF-32

n , n

nn . n , n :

'
>>> with open(r"file.txt", "w", encoding="utf-16")
as f:
f. wri te ("")

>>> with open(r"fi1e.txt", "r", encoding="utf-16") as f:


for 1ine in f:
print(repr(line))
''

utf-16-1e, utf-16-be, utf-32-1e

utf-32-be

, n .
n

"strict"

errors

( ;

no

),

"rep\ace" (
"ignore" (

\ufffd),

),
n &#;)

15.2.

"xmlcharrefreplace" (
"backslashreplace" ( n

\uxxxx).

open () ,

.
. \ :

c1ose () - . ,
, .
n
. ,

Python 3.2

n :

2.6,

n n

"ResourceWarning: unclosed fi1e".

Python

n , n
. :

with open(r"fi1e.txt", "w", encoding="cp1251") as f:


f.write("Cpoa") #
#

write (<>) -

n , .
n n .

266

/.

Python 3

,
.
. :

>>>
>>>
>>>
15
>
>>>
>>>
>>>
15
>>>

#
f = open(r"fi1e.txt", "w", encoding="cp1251")
f.write("Cpoa1\nCpoa2") #

#
f .c1ose ()
#
f = open(r"fi1e.txt", "wb")
f .write (bytes ("1 \r2", "1251"))

f .write (bytearray("\nCpoa",

"1251"))

> f.c1ose()

writelines (<>) - .
,
. ,
. :

>>>
>>>
>>>
>
>>>
>>>
>>>
>>>
>

#
f = open(r"fi1e.txt", "w", encoding="cp1251")
f.write1ines(["Cp~a1\n",

"2"])

f.c1ose()
#
f = open(r"fi1e.txt", "wb")
arr = [bytes ( "1 \n", "1251"), bytes ( "2",
f.write1ines(arr)
f.c1ose()

"1251")]

read( [<>])- .
, ,

,
:

>>> #
>>> with open(r"fi1e.txt", "r", encoding="cp1251") as f:
f .read ()
'1\n2'

>>> #
>>> with open(r"fi1e.txt", "rb") as f:
f. read ()
b'\xd1\xf2\xf0\xee\xea\xe01\n\xd1\xf2\xf0\xee\xea\xe02'
,
. ,
. :

>>> #
>>> f = open(r"fi1e.txt", "r", encoding="cp1251")

15.

> f.read(B)

267

'l\n'

> f.read(B)
'2'

>>> f .read(B)

>>> f .close ()

+ readline ( [<> J) -

, , -
. .
. ,

.
. :

>>> #
>>> f = open(r"file.txt", "r", encoding="cp1251")
>>> f.readline(), f.readline()
('l\n',

'2~)

>>> f.readline()

> f. close ()
>>> #
>>> f = open(r"file.txt", "rb")
>>> f.readline(), f.readline()
(b'\xdl\xf2\xf0\xee\xea\xe01\n', b'\xdl\xf2\xf0\xee\xea\xe02')
> f . readline ( )
#
''

>>> f.close()
,
,

(\n),

. ,
, ,
. ,
. :

>>> f = open(r"file.txt", "r", encoding="cpl251")


>>> f.readline(2), f.readline(2)
( '', '')
>>> f.readline(l00) # ,

100

'al\n'

>>> f. close ()

readlines () -

, .
. ,

. ,
, - -

bytes. :

>>> #
>>> with open(r"file.txt", "r", encoding="cp1251") as f:
f. readlihes ()

268 '
[ 1 l\n 1 ,

/.

Python 3

>>> ~
>>> with open(r"file.txt", "rb") as f:
f. readl ines ()
[b 1 \xdl\xf2\xf0\xee\xea\xe01\n 1 , b 1 \xd1\xf2\xf0\xee\xea\xe02 1 ]

+ _ next _

() -

, ,

Stopiteration.

>>> #
>>> f = open(r"file.txt", "r", encoding="cpl251")
>>> f. next (), f. next ()
1
1
(
! \n 1 ,
2 1 ) .
>>> f. next () #
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
f. next () #
Stopiteration
> f .close ()

_next_()
for. for _ next_ ().

>>> f = open(r"file.txt", "r", encoding="cpl251")


>>> for line in f: print(line.rstrip("\n"), end=" ")
! 2

> f. close ()

flush () - ;

fileno () - .
2, . . stdin, 1 -
stdout, 2 -
stderr. :

>>> f = open(r"file.txt", "r", encoding="cpl251")


> f. fileno ()
#
3

> f.close()

+ truncate ( [<>]) -

. . :

>>> f = open(r"file.txt", "r+", encoding="cpl251")


> f . read ( )
1

l\n2

>>> f.truncate(5)
5

15.

269

>>> f.close()
>>> with open(r"file.txt", "r", encoding="cp1251") as f:
f .read ()
''

tell () -

. ,

Windows

tell () \r

, .
:

>>> with open(r"file.txt", "w", encoding="cp1251") as f:


f. write ( "String1 \nString2")
15
>>> f = open(r"file.txt", "r", encoding="cp1251")
>>> f.tell()
#

>>> f.readline()
'String1\n'
> f.tell()

9 (8 + '\r'),

8 !!!

>>> f. close ()
, ,
:

>>> f = open(r"file.txt", "rb")


>>> f.readline() #
b'Stringl\r\n'
> f. tell ()
#
9

>>> f.close()

seek (<> [, <>]) - ,


<> <>. <~>
io :

io.SEEK_SET - ( );

io. SEEK_ cuR

1 -

io. SEEK_ END

2-

>>> import io
>>> io.SEEK_SET, io.SEEK_CUR, io.SEEK END
(0, 1, 2)

seek ():

>>> import io
>>> f = open(r"file.txt", "rb")
>>> f.seek(9, io.SEEK_CUR) # 9
9

270

1.

Python 3

>>> f.tell()

9
>>> f.seek(O,

io.SEEK_~ET)

>>> f. tell ()

>>> f .seek(-9, io.SEEK_END)

-9

>>> f.tell()
7

>>> f .close ()
:

+
+
+

narne- ;
mode- , ;
closed- True, , False . :
>>> f = open(r"file.txt", "r+b")
>>> f.name, f.mode, f.closed

('file.txt', 'rb+', False)


>>> f.close()
>>> f.closed

True

encoding- ,
. ,
, . . .
. :

>>> f = open(r"file.txt",
>>> f.encoding

"",

encoding="cpl251")

'cpl251'
>>> f.close()

stdout . encoding

,
. ,

Python She\1

encoding "866",
IDLE- "1251". :

>>> import sys


>>> sys.stdout.encoding
'1251'

buffer- .
.
. :

>>> f = open(r"file.txt", "w", encoding="cp1251")


>>> f.buffer.write(bytes("Cpoa", "1251"))
6

>>> f.close()

15.

271

15.3. os

os

.
.

Windows

> import os
>>> os.name
'nt'

Windows

n(<

>,

<>[,

mode=Oo777])-

name.

"nt":

os:

, .

Windows

OSError. <>

1 ):

os. _ROONLY -

os .O_WRONLY- n;

os. _RDWR-

os. _APPEND- ;

os. _CREAT- , ;

os. _TRUNC-

os .O_BINARY- ;

os. _- . Windows -

. , . , :

>>>
>>>
>>>
>>>

import os
#
mode = os.O_WRONLY 1 os.O_CREAT 1 os.O_TRUNC
f = os.open(r"file.txt", mode)
os.write(f, b"Stringl\n") # n

>>> os.close(f)

>>> mode = os.O_WRONLY 1 os.O_CREAT 1 os.O_APPEND


>>> f = os.open(r"file.txt", mode)
>>> os.write(f, b"String2\n") #

> os.close(f)

>>> f = os.open(r"file.txt", os.O_ROONLY)


>>> os.read(f, 50)
# 50
b'Stringl\nString2\n'
> os.close (f)
# ~

272

/.

Python 3

>>> f = os.open(r"file.txt", os.O_RDONLY 1 os.O_BINARY)


# 50
>>> os.read(f, 50)
b'Stringl\r\nString2\r\n'
#
> os.close(f)

rd.(<>,

<

>)-

. . :

>>> f = os.open(r"file.txt", os.O_RDONLY)


>>> os.read(f, 5), os.read(f, 5), os.read(f, 5), os.read(f, 5)
(b'Strin', b'gl\nS', b'tring', b'2\n')
>>> os.read(f, 5)
#
''

> os.close(f)

write (<>,

<

>) -

. ;

+
+

close (<>) - ;
lseek (<>,

<>,

<>)

<> <>.

. <>
:

os. SEEK_ SET - ;

os.SEEK_CUR

os. SEEK_ END 2 -

1 -

>>> f = os.open(r"file.txt", os.O RDONLY 1 os.O_BINARY)


>>> os.lseek(f, , os.SEEK_END) #
18
>>> os.lseek(f, , os.SEEK_SET) #

>>> os.lseek(f, 9, os.SEEK_CUR) #

>>> os.lseek(f,

os.SEEK_CUR) #

>>> os.close(f)

+
+

du(<>)- ;

fdopen

(<>

[,

<>

[,

< >]

]) -

. <> < > ,

open ( ) . :

>>> fd
> fd

os.open(r"file.txt", os.O_RDONLY)

>>> f = os.fdopen(fd, "r")


>>> f.fileno() #
3

15.

273

> f.read()
'Stringl\nString2\n'
>>> f.close()

15.4.

String/0

Bytes/0

StringiO io n .

n n n n.
:

newline=None])

StringiO([<Haaoe >][,

ri n , n .
n "". ,
, :

close () - "". , "" , n


closed. True, "" , False n ;

getvalue () - "" :
>>> import io
#
> f = io.StringiO("Stringl \n")
>>> f .getvalue ()
#
'Stringl\n'
>>> f.close()
#

+ tell () - n "";
+ . seek (<> [, <> J ) - n,

<> n <>. n <>


:

- "" (

2 - "".

no );

- n ;

seek ()

tell ():

>>> f = io.StringiO("Stringl\n")
>>> f.tell()
#

>>> f.seek(O, 2)

>>> f. tell ()
8

>>> f.seek(O)

>>> f. tell ()

>>> f.close()

write (<>) -n "":


>>> f = io.StringiO("Stri~gl\n")
>>> f.seek(O, 2)
#
8

>>> f.write("String2\n") #

/.

Python 3

nI

> f.getvalue()
'Stringl\nString2\n 1
> f.close()

writelines (<>) - "":


>>> f = io.StringiO()
>>> f.writelines(["Stringl\n", "String2\n"])
>>> f.getvalue()
#
1
Stringl\nString2\n 1
#
> f.close()

read ( [< > J) - "". n


, "" n "
". n ,

. "",
n . :

>>> f = io.StringiO("Stringl\nString2\n")
> f.read()
'Stringl\nString2\n'
>>> f.seek(O) #

>>> f.read(S), f.read(S), f.read(S), f.read(S), f.read(S)


1
(
Strin' , 1 gl \nSt 1 , 1 ring2' , '\n' , 1 ' )
>>> f.close() #

readline ( [< >]) -

"" ,t< n

. n .
n . n , n

. "" n
. :

>>> f = io.StringiO("Stringl\nString2")
>>> f.readline(), f.readline(), f.readline()
( 'Stringl \n' , 'String2' , ' 1 )
>>> f.close() #
n , n

nop,

(\n),

""

"" n . ,
n, ,
. ,
. :

>>> f = io.StringiO("Stringl\nString2\nString3\n")
>>> f.readline(S), f.readline(S)
( 'Strin' , 'gl \n' )
>>> f.readline(l00) # , 100
'String2\n'
>>> f.close()
#

15.

275

readlines ( [ < > J) -

""

. ,

. .
, . :

> f

= io. StringiO ( "Stringl \nString2\nString3")


>>> f.readlines()
[ 'Stringl \n', 'String2\n', 'String']
>>> f.close() # m

, .

\n.

. :

> f

= io. StringiO ( "Stringl \nString2\nString3")


>>> f.readlines(l4)
[ 'Stringl \n', 'String2\n']
>>> f.seek(O) #

>>> f.readlines(17)
[ 'Stringl \n', 'String2\n', 'St.ring']
>>> f.close() # m

_next_ () - . "
Stoprteration. :

"

>>> f

io.StringiO("Stringl\nString2")
next (), f. next ()
('Stringl\n', 'String2')
>>> f. next ()
. . . ...
Stopiteration
>>> f.close() # m
=

> f.

_next_()

for. for

next

().

>>> f = io. StringiO ( "Stringl \nString2")


>>> for line in f: print(line.rstrip())
Stringl
String2
>>> f.close() #

+
+

flush () - "";
truncate ( [< > J ) -

"" -

. :

> f = io.StringiO("Stringl \nString2\nString3")


>>> f.truncate(15)
15
>>> f. getvalue ()
'Stringl\nString2'
> f.close()

276

/.

Python 3

, "" :

> f = io. StringiO ( "String1 \nString2\nString3")


>>> f.seek(15)
#
15
>>> f. truncate ()
#
15
>>> f .getva1ue ()
#
'String1\nString2'
> f.c1ose()
#
StringiO ' .
,

Bytesro io.

tsi([< >])

Bytesro

stringiO,

" , .
:

>>> import io
#
> f = io.BytesiO(b"String1\n")
>>> f.seek(O, 2)
#

>>> f.write(b"String2\n") #

>>> f .getva1ue ()
b'String1\nString2\n'
> f.seek(O)

> f. read ( )
b'String1\nString2\n'
>>> f.c1ose()

3.2, Bytesrq getbuffer (),


meinoryview.

, (

to1ist ()) ( tobytes () ). :


>>> f = io.BytesiO(b"Python")
>>> buf = f.getbuffer()
>>> buf[O]
#

''

>>> buf[O] = b"J"


#
> f .getva1ue ()
#
b'Jython'
> buf.to1ist()
# n
[74, 121, 116, 104, 111, 110]
>>> buf.tobytes()
# n bytes
b'Jython'
>>> f.c1ose()
#

15.

277

15.5. .

UN1X

( )

- , -

: :
t

r - , ;

w- , ,
. ;

- , ,
.

-rw-r--r-

(rw-)

, , .

( ).

--

(r--)-

(r--)

( ).
:

drwxr-xr-x

(r-x).

(d) , .
(rwx), -

,.

().
, .

-rw-r--r--

644.

, (.
,

7.

. ,

rw-r--r--

15.1 ).

110 100 100,

4 4. , ,

1,

- .

15.1.

000

---

100

r--

001

--

101

r-x

010

-w-

11

rw-

011

-wx

111

rwx

278

/.

n n n

Python 3

access ()

os. :

ss(<>,

<>)

True,

n n,

False

<> , n
:

os.F_o- :

>>> import os
>>> os.access(r"file.txt", os. F_)
True
>>> os. access ( r"C: \book", os.F_OK)
True
>>> os.access(r"C:\book2", os.F_OK)
False

os

#
#

os. R_ - n ;

os. w_- n ;

os. _- n, ' .

n,

chmod () os. :
hmd(<>,

< >)

n ,

( ):

>>> os.chmod(r"file.txt",

777)

stat.

15.6.

shutil:

copyfile (< >, < >) -

. (n, n) n.
, n. n,

>>>
>>>
>>>
>>>

IOError. :

import shutil
#
shutil.copyfile(r"file.txt", r"file2.txt")
# :
shutil. copyfile (r"file. txt", r"C: \book2\file2. txt")
...
IOError: [Errno 2] No such file or directory:
'C:\\book2\\file2.txt'

15.

(<Konpyeiir >,

279

< >)

n n . n

n n. , nn.
n,

>>> shutil.copy(r"file.txt",

+ 2 (<n

>,

IOError.

r"file.txt~)

< >)

n n

. , nn.
n,

IOError.

>>> shutil.copy2(r"file.txt", r"file4.txt")

move (< >, < n>) -

n ,

. , nn.
n,

IOError. ,
WindowsError. n

Windows

C:\book\test:

file4.txt

>>> shutil.move(r"file4.txt", r"C:\book\test")


n n

rename (< >,

<

>)

n .

, n

os:

Windows

WindowsError. n

import os #
try:

os.rename(r"file.txt", "file4.txt")
except OSError: # WindowsError OSError
print (" n")
else:
print (" n n")

remove (< >) unlink(<y >)- n .


, n

WindowsError.

Windows

>>> os.remove(r"file2.txt")
>>> os.unlink(r"file4.txt")

os .path n , n n

, n . :

exists (<>) - n n . 'l


True, n , False n :

>>> import os.path


>>> os.path.exists(r"file.txt"), os.path.exists(r"file2.txt")
(True, False)
>>> os.path.exists(r"C:\book"), os.path.exists(r"C:\book2")
(True, False)

getsize (< >) -

. ,

Windows WindowsError:

280
>>> os.path.getsize(r"file.txt") #
18
>>> os.path.getsize(r"file2.txt") #
...
WindowsError: [Error 2]

getatime

(<

>)

/.

Python 3

'file2.txt'

. ,

WindowsError.

Windows

>>> import time


# time
>>> t = os.path.getatime(r"file.txt")
>>> t
1304111982.96875
>>> time.strftime("%d.%m.%Y %H:%M:%S", time.localtime(t))
'30.04.2011 01:19:42'

getctime (< >)- .


, .

Windows

WindowsError. :

> t = os.path.getctime(r"file.txt")
>>> t
1304028509.015625
>>> time.strftime("%d.%m.%Y %H:%M:%S", time.localtime(t))
'29.04.2011 02:08:29'

getmtime (< .>)- .


, .

Windows

WindowsError. :

> t = os.path.getmtime(r"file.txt")
>>> t
1304044731.265625
>>> time.strftime("%d.%m.%Y %H:%M:%S", time.1ocaltime(t))
'29.04.2011 06:38:51'
, ,

stat () os.
stat_result, : st_mode, st_ino, st_dev,
st_nlink, st_uid, st_gid, st_size, st_atime, st mtime st ctime.
stat 1) 15.4.

rri'~~~~~1s~4~r;-p~~;~:~~ri.d.ri~~~~~~-~~-;;~~~~ _~;_;t:(';~~-~~~
.................... ;,;,,,;;;,,,,,,;.. ,;,,,,,;,, . :.................'.; ...'.;;;,,;,,.,,;,;;,,;,,,,,;,,,,;;,;,;;,,,;,,,,,,;,,,, .........=::.;:-:;......... : :::: ..........;......... .........................

>>> import os, time


>>> s = os.stat(r"file.txt")
>>> s
nt.stat resu1t(st_mode=33060, st ino=2251799813878096, st_dev=O,
st_n1ink=1, st_uid=O, st_gid=O, st_size=18, st_atime=1304111982,
st_mtime=1304044731, st_ctime=l304028509)
>>> s.st size
#
18

15.

281

>>> t = s.st_atime #
> time.strftime("~d.%m.'iiY %:%:'S", time.1oca1time(t))
'30.04.2011 01:19:42'
>>> t = s.st_ctime #
> tlme. strftime ( "'Cd. 'm. ~. ' : %: 'tS", time .1ocalt ime (t) )
'29.04.2011 02:08:29'
>>> t = s.st_mtime #
> time.strftime("%d.%m.c,y 'isH:%M:%S", time.1oca1time(t))
'29.04.2011 06:38:51'
u

utime

1)

os. u :
utime(<y

>,

utimei<y

>,

None)
(< >,

<

>))

None,

. u utime 1)
, . . ,

Windows WindowsError. u

utime()

15.5.

~~~~~; 15:5~ ~~~ ~~ri~~~;~~~~~ v~~~~~-~t;;;,;

... ................................................................................:..............

: ,;

;.,,;

............ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..

.. ,...........................: .......................:................................................................................

>>> import os, time


>>> os.stat(r"fi1e.txt")
#
nt.stat_resu1t(st_mode=33060, st_ino=2251799813878096, st_dev=O,
st_n1ink=1, st_uid=O, st_gid=O, st_size=18, st_atime=1304111982,
st_mtime=1304044731, st_ctime=1304028509)
>>> t = time.time() - 600
> os.utime(r"fi1e.txt", (t, t)) # 600
>>> os.stat(r"fi1e.txt")
nt.stat resu1t(st_mode=33060, st ino=2251799813878096, st_dev=O,
st_n1ink=1, st_uid=O, st_gid=O, st_size=18, st_atime=1304112906,
st_mtime=1304112906, st_ctime=1304028509)
>>> os.utime(r"fi1e.txt", None)
#
>>> os.stat(r"fi1e.txt")
nt.stat_resu1t(st_mode=33060, st ino=2251799813878096, st_dev=O,
st_n1ink=1, st_uid=O, st_gid=O, st_size=18, st_atime=1304113557,
st_mtime=1304113557, st_ctime=1304028509)

15.7.

os .path:

abspath (< >) -

. :

>>> import os.path


>>> os.path.abspath(r"fi1e.txt")
'C:\\book\\fi1e.txt'

282

/.

Python 3

> os.path.abspath(r"folderl/file.txt")
'C:\\ook\\folderl\\file.txt'

>>> os.path.abspath(r" .. /file.txt")


'C:\\file.txt'
, .

sep os. path.

Windows:

>>> os.path.sep

'\\'

Windows

.
. :

> "C:\\temp\\new\\file.txt"
'C:\\temp\\new\\file.txt'
> r"C:\temp\new\file.txt"
'C:\\temp\\new\\file.txt'
>>> "C:\temp\new\file.txt"
'C:\temp\new\xOcile.txt'

!!

, ,

>>> r"C: \temp\new\"


# !!!
SyntaxError: EOL while scanning string literal
>>> r"C:\temp\new\\"
'C:\\temp\\new\\\\'
,

. , .
. . ,
. :

>>> "C:\\temp\\new\\"
'C:\\temp\\new\\'
> r"C:\temp\new\\"[:-1]
'C:\\temp\\new\\'

isabs (<>) - True, , False


:

>>> os.path.isabs("file.txt")
False
>>> os.path.isabs(r"C:\book\file.txt")
True

basename (<>) - :
>>> os.path.basename(r"C:\book\folderl\file.txt")
'file.txt'
>>> os.path.basenarne(r"C:\book\folder")
'folder'
> os.path.basename("C:\\book\\folder\\")

15.

t dirname (<>) -

283

> os.path.dirname(r"C:\book\folder\file.txt")
'C:\\book\\folder'
>>> os.path.dirname(r"C:\book\folder")
'C:\\book'
> os .path.dirname (":\ \book\ \folder\ \")
'C:\\book\\folder'

split (<>) -

: ~

>>> os.path.split(r"C:\book\folder\file.t~t")
('C:\\book\\folder', 'file.txt')
>>> os.path.split(r"C:\book\folder")
(':\ \book', 'folder')
>>> os.path.split("C:\\book\\folder\\")
('C:\\book\\folder', '')

splitdrive (<>) - .
:

>>> os.path.splitdrive(r"C:\book\folder\file.txt")
(':', '\\book\\folder\\file.txt')

split.ext (<>) - : ,
, ( ):

>>> os.path.splitext(r"C:\book\folder\file.tar.gz")
('C:\\book\\folder\\file.tar', '.gz')

j oin (<l> [, ... , <N> J ) - :


>>> os.path.join("C:\\", "book\\folder", "file.txt")
'C:\\book\\folder\\file.txt'
>>> os.path.join(r"C:\\", "book/folder/", "file.txt")
'C:\\\\book/folder/file.txt'
.
. ,

nonnpath () :

>>> = os.path.join(r"C:\\", "book/folder/", "file.txt")


>>> os.path.normpath(p)
'C:\\book\\folder\\file.txt'

15.8.

, ,

fileno (),
stdin, 1 -

2,

. .

stdout,

2-

std~rr.
. ,

stdout stderr wri te (),


stdin readline (),

. ,

284

/.

Python 3

, .

(
j1'~;;:~~~1:5i':h~p~~~ri~~~~~~;~6~ti~';~

15.6).

. . . . . . . . .:. . .,. . . ::.............................

. ..................................... ;.

: ,;,,,,, < ; : .......... ~ :: :.;,.,;.:_.;;;,,:;,; ;.;,... ;;,..,,,;:. ;:.: ..:;;;;..... ::,.. ::: . ::;. . .-;;,;,,, . :.-~ .............. :.. :.;.. :: ... : ...... ;.......................................................... .

>>> import sys


>>> tmp_out = sys.stdout
>>> f = open(r"file.txt",
>>> sys.stdout = f

"")

>>>

")

rint("

>>> sys.stdout = tmp_out


>>> print ("

#
#
#
#

sys
sys.stdout

")

>>> f. close ()

tmp_ out.

print ()
file,

, :

>>> f = open(r"file.txt",
>>> rint("

"")
",

file=f)

>>> f.close()

stdin

. u

input 1)

. u

EOfError.

15.7).

rii'~~;~;1!;:-;1;:~p~~ri~~~~~

;::.:. ;~;:.=......... :.:~ ...... ::.... :..~;,,;;; ..~ .. ~-~~- .. ~~::.~~::.~;;,;,-;. ~~.: ..~.;;:

# -*- coding: utf-8 -*import sys


tmp_in = sys.stdin
f = open(r"file.txt", "r")
sys.stdin = f
while True:
try:
line = input ()
print(line)
except EOfError:
break
sys.stdin
tmp_in
f .close ()
input ()

#
#
#

#
#
#
#
#
#

sys.stdin

, ,

,

false

isatty ().

True,

15.

285

>>> tmp_in

~ sys.stdln
open(r"file.txt", "r")
>>> sys.stdin ~ f
> sys.stdin.isatty()
Falsc:
>>> sys.stdin ~ tmp_in
>>> sys.stdin.isatty(l
True
> f.close()

>>> f

#
#

sys.stdin

#
#

n / n .

tests.py

C:\book

, n

15.8.

: 15.8. n tests.py
i ...............,, .. , ...................................................; .................................; ... : .... ;;,,,,,, ............ : ............. , .. ; .................. ;:~ ................;,,,,,,;,,,, .......................................... ;... . ..................... "'

# -*- coding: utf-8 -*while True:


try:
line ~ input ()
print ( line 1
except EOFError:
break
n n n n, n

: \book. n

file.txt,

cd

n :

C:\Python32\python.exe tests.py < file.txt


n .

< >.

tests.py

# -*- coding: utf-8 -*print ("String")

n nn

file.txt,

n :

C:\Python32\python.exe tests.py > file.txt


file.txt

nn.

, n

n :

C:\Python32\python.exe tests.py >> file.txt


n

stdout

n n

. , n, n

Windows

\r

(n )

, n n

\r,

\n

(n ).

nn .
n n (

15.9).

286

/.

Python 3

!;~;~-~/"15:::::~~~~~;~~ ~~;~6~;~~~~-~'~~;;:::::J
~.;~

.. :.;......

;,,,;;

.............. ...... ,,,,;,,,;;:...... :.........


~

;,;;,;;;,,;,,,,,,,~

# -*- coding: utf-8 -*import sys, time


for i in range 15, 101, 5):
sys.stdout.writel"\r
sys.stdout.f1ushl)
time.s1eepll)

..:...;:_.,,,;,,.....................................................................

%s%%" % i) #

#
#

........................................................... ............................................:

sys.stdout.writel"\rpoecc \n")

input 1)
.
.

flush 1).

15.9.


pickle shelve. pickle :

dump 1<>,

<> [,

<>] [,

fix _ imports=True] ) -

. <>
, .
:

>>>
>>>
>
>>>
>>>

import pickle
f = openlr"file.txt", "wb")
obj = ["", 12, 3)]
pickle.dumplobj, f)
f. close 1)

load 1) - . <>
. . :

load 1<> [, fix _ imports=True] [, encoding="ASCII"]


[, errors="strict"])
:

>>> f = openlr"file.txt", "rb")


>>> obj = pickle.loadlf)
> obj
[ ' ' , 12, 3) ]
>>> f.closel)
,
dump 1).

15.1 .

[{ij~~i.!~~j~:i~;-~~~~~~:~~]~~~~~~~~3:?~~~~~~:.::.:::::: . : : : .: :. .: :. :: : : : : :. : :.: : .:.:. ::. :.: . .:.:.-:..: :.: : :.: . : :. : : . .::. :. . :. . ::.:'i
>>> objl = ["", 12, 3)]
>>> obj2 = 11, 2)
>>> f = openlr"file.txt", "wb")

15.

287

#
#

>>> pick1e.dump(objl, f)
>>> plck1e.dump(obj2, f)
> f. c1ose ()

1oad ()

15.11).

;: ..

:.t:t!':"''''''''''''."'''''':~:.:::;.::::.::::,

..:.:~:.:::.::.:~.-.::~::::: ..... ,.................................... ~

~ -r 15.11 ::i!

< . . . ' ' '

~........................................ ;.... ' .. :.". :. ;:::;' ;; :;. :: ... :..'~=.... ,;;; .. .::' ;; ,:,,; . : .... :' :: ....'. ;, ...... ;;; ~................ ; ~ :~.; ...:.;~:; ;; ,',, .:.': :.:; :........ ; ..,:, .... '... ...

>>> f = open(r"fi1e.txt", "rb")


>>> obJ1 = pick1e.1oad(f)
>>> obj2 = pick1e.1oadlfl
> obj1, obj2
( [ ' ' , ( 2, 3) ] , (1, 2) )
> f .c1ose ()

#
#

''' .............. ' ..... :

dum(<>)

Pick1er.

:
ik1r(<>[,

<>][,

fix~imports=True])

>>>
>
>>>
>>>
>

f = open(r"fi1e.txt", "wb")
obj =["", (2, 3)]
pk1 = pick1e.Pick1er(f)
pk1.dump(obj)
f .c1ose ()

1oad () Unpick1er.

fix imports=True] [, encoding="ASCII"]


[, errors="strict"])

Unpick1er(<a>[,

>>> f = open(r"fi1e.txt", "rb")


>>> obj = pick1e.Unpick1er(f) .1oad()
> obj
[ ' ' , (2, 3) ]
> f. c1ose ()

pick1e

. :

dumps (<> [, <>] [, fix~imports=True]) -

.
(

3).

>>> obj1 = [1, 2, 3, 4, 5]


#
>>> obj2 = (6, 7, 8, 9, 10)
#
>>> pick1e.dumps(obj1)
b'\x80\x03]q\x00(K\x01K\x02K\x03K\x04K\x05e.'
>>> pick1e.dumps(obj2)
b'\x80\x03(K\x06K\x07K\x08K\tK\ntq\x00.'

288

/.

Python 3

encoding="ASCII"] [,
1ds(<
>[,
fix_imports=True] [,
errors="strict"J)-
. :

>>> pickle.1oads(b'\x80\x03]q\x00(K\x01K\x02K\x03K\x04K\x05e.')
[1, 2, 3, 4, 5]

>>> pick1e.loads(b'\x80\x03(K\x06K\x07K\x08K\tK\ntq\x00.')
(6, 7, 8, 9, 10)

she1ve (

) , .

pick1e,

, dL

no

she1 ve

open ().

open (<

>

[, flag="c"] [, protoco1=None] [, writeback=Fa1se])

+
+
+

r -

flag :

w- -;
- ( ). , ~
;

n-

. , . ,

open ()

. :

c1ose () -

t.

>>> import she1ve


>>> d = she1ve.open("d1")
>>> d["obj1"] = [1, 2, 3, 4, 5]
> d["obj2"]. = (6, 7, 8, 9, 10)
>>> d["obj1"], d["obj2"]
([1; 2, 3, 4, 5], (6, 7, 8, 9, 10))
>>> d.c1ose()

+
+
+

#
#
#
#
#
#

keys () - ;
va1ues () - to ;
items () -

, .

, . :

>>> d = she1ve.open("d1")
>>> d.keys(), d.values()
(KeysView(<she1ve.DbfilenameShe1f object at Ox00FE81B0>),
ValuesView(<she1ve.Dbfi1enameShelf object at Ox00FE81B0>))
>>> 1ist(d.keys()), 1ist(d.va1ues())
(['obj1', 'obj2'], [[1, 2, 3, 4, 5], (6, 7, 8, 9, 10)])

15.

. 289

> d.items()
ItemsView(<shelve.DbfilenameShelf object at OxOOFEBlBO>)
>>> list(d.items())
[ ( ' obj 1' , [ 1 , 2, 3, 4 , 5] ) , ( ' obj 2 ' , ( , 7, 8 , 9, 1 ) ) ]
> d.close()

get

(<>

< >]

[,

)-

, . ,

None

, n;

setdefaul t (<> [, < >] ) ---: n,


, . ,
, ,

. n ,

.+

(<>

[,

<

>]

None;

)-

. , >
n. , n ,

KeyError;

popitem()-

n,

+
+

KeyError;

clear () - . ;
update () -

. , n
n-. :
udt(<1>=<l>[,

... ,

<N>=<N>])

udt(<>)

udt(< >)
udt(< n >)

del

len ()

n , n

in

n . :

>>>
>>>

shelve.open("dl")

len(d)

>>> "objl" in d
True
> del d [ "obj 1"]
>>> "objl" in d
False
>>> d.close()

15.10.

getcwd () -

os:'

. ,

, n n . ,

10 . 1349

290

/.

Python 3

, ,
, .

>>> import os
> os. getcwd ()
1
C:\\book 1

chdir (<

>) - :

> os.chdir("C:\\book\\folderl\\")
>>> os.getcwd()
'#
1
C:\\book\\folderl 1

mkdir (<

>

[,

< n>])

, . ,
( 777).

~ i :
>>> os .mkdir ( "newfolder")

rmdir (< >) -

, Windows WindowsError.

newfolder:

>>> os.rmdir("newfolder") #

listdir (<>) - :
> os .listdir (":\ \book\ \folder1 \\")
1
[
file1. txt 1 , 1 file2. txt 1 , 1 file. txt 1 ,

folder1 1 ,

folder2 1 ]

walk () - . :
wlk(<

>[,

topdown=True] [, onerror=None]

[, followlinks=False])

walk () .

: ,
. ,
.

topdown .
True ( ), -

> for

(,

d, f) in os.walk("C:\\book\\folder1\\"): print(p)

C:\book\folderl\
C:\book\folderl\folderl_1
C:\book\folder1\folder1_1\folder1_1_1
C:\book\folder1\folder1- 1\folder1-1-2
C:\book\folder1\folder1_2

:

>>> for

topdown False,

(, d, f) in os.walk("C:\\book\\fo1der1\\", Fa1se):
print(p)

15.

291

C:\book\fo1der1\folder1- 1\folder1-1-1
c:\book\fo1der1\folderl 1\folder1 1 2
C:\book\fo1der1\folder1~1

C:\book\folder1\folder1_2
C:\book\folder1\
n
. n , . .

rmdir ()

n . :

import os
for (, d, f) in os.walk("C:\\book\\folder1\\", False):
for file_name in f: #
os.remove(os.path.join(p, file_name))
for dir_name in d: #
os.rmdir(os.path.join(p, dir_name))
!
.

walk ()

, .

rmtree ()

shutil.

:
rmtree(<ny>[,

< >[,

< >]])

n < >

False

no

True,

), n

-. n
.
:

import shutil
shutil. rmtree (":\ \book\ \folder1 \\")
,

listdir ()

n .

, n n, n
5. path:

isdir (<>) -

True,

, False n

>>> import os.path


>>> os .path. isdir (r"C: \book\file. txt")
False
>>> os.path.isdir("C:\\book\\")
True

isfile (<> J

True,

>>> 05 .path. i5file (r"C: \book\file. txt")


True
>>> 05.path.i5file("C:\\book\\")
False

Fal5e

292

islink(<Oe>) ~

False

Python 3

, fl

n . n,

True,

/.

false.

listdir ()

n .

n n , n

glob (<>)

glob.

glob ()

n n n

+
+
+

? ~ ;
*~ ;
[<> J ~ n , n.
n n .

n n , n
. n

glob ()

15.12.

: 15, 12. 11Q.t!!'4113.~l


........ . .. ; .. : .........................................................: ;,,,;;, ;,,,,;,;,;,,;;; ~ =.;,,,:;;,:,,,,,,,,;;,,,,,,.~ ; ................................................................. .

>>> import os, glob


>>> os.listdir("C:\\book\\folderl\\")
['file.txt', 'filel.txt', 'file2.txt', 'folderll', 'folderl 2',
'index.html']
>>> glob.glob("C:\\book\\folderl\\*.txt")
[':\ \book\ \folderl \ \file. txt', ':\ \book\ \folderl \ \filel. txt',
'C:\\book\\folderl\\file2.txt']
> glob.glob("C:\\book\\folderl\\*.html") #
['C:\\book\\folderl\\index.html']
>>> glob.glob("folderl/*.html")
#
['folderl\\index.html']
> glob.glob("C:\\book\\folderl\\*[0-9] .txt")
['C:\\book\\folderl\\filel.txt', 'C:\\book\\folderl\\file2.txt']
> glob.glob("C:\\book\\folderl\\*\\*.html")
['C:\\book\\folderl\\folderl_l\\index.html',
'C:\\book\\folderl\\folderl_2\\test.html']
n n. n
, n. n n

n , .

16

SQLite

n
n

no

n shelve.

n pickle, , dm, n
n

no

. n ,

n dm.
n , n
.

2.5,

SQLite.

Python

sqlit n

, n - n, . .

n .
sqlite.dll (n n

SQLite -

C:\Python32\DLLs) n,
Python). ,

n (n,

SQLite

SQLite

n n, n

n n n.

SQLite

SQLite

n .

Python,
Python n SQL
(Structured Query Language- n) n
SQLite. n SQL-anpoco n n sqlite.exe,
n SQLite . http://www.sqlite.org/
download.html , n n. n

sqlite.exe , _ (n,

C:\book).

16.1.

n l. n .
n .

cmd

n . , . -

C:\book,

n :

cd C:\book
n:

C:\book>

294

/. Python 3

866.
1251, :

chcp 1251
, . .

Windows-1251.

Lucida Console.

. , . n

chcp.

C:\book>chcp
:

1251

n :

C:\book>sq1ite3.exe

testdb.db

testd.d

. ,
. :

SQLite version 3.7.6


Enter ".he1p" for instructions
Enter SQL statements teiminated with
sql"ite>

";"

.
( ) .

"sqlite> " SQL-. SQL-

<Enter>,
SQLite:

"

... > ".

sq1ite> SELECT sq1ite_version();


3.7.6
sq1ite> SELECT sq1ite_version()
... >
3.7.6

SQLite

.
.

/*

* 1.

. .
.
, . :

sq1ite> --
sq1ite> /* */
sq1ite> SELECT sq1ite_version(); --
3.7.6

SQL-

16. SQLite

295

sqlite> SELECT sqlite_version();


3.7.6

SQLite

/* n SQL-I

*/

.exit

.quit.

16.2.

SQL-:

CREATE

< nl>

L [IF NOT EXISTS]


] < > (

TEPORARY]

[< >.

[<n >]

[<n>],

[< ~>]

[<>],]

... ,

< N>

[< >]

);

CREATE TEMPORARY,

. :

sqlite> CREATE L trnpl (polel);


sqlite> CREATE TEPORARY L trnp2 (polel);
sqlite> . taes
trnpl trnp2
. n

. taes

. sqlite.exe
SQL-apoca:

sqlite>
... >
... >
... >
... >
... >
trnpl
trnp2

SELECT n FRO sqlite_rnaster


WHERE type IN ('tale', 'view') AND n NOT
UNION ALL
SELECT n FROM sqlite_ternp_rnaster
WHERE type IN ('tale', 'view')
ORDER 1;

LIE

'sqlite_%'

IF NOT Exrss ,

, .

IF NOT Exrss , . :
sqlite> CREATE L trnpl (pole3);
Error: t trnpl already exists
sqlite> CREATE L IF NOT EXISTS trnpl
sqlite> PRAGA tae_info(trnpl);
1polell 1 11

(l);

SQL- PRAGA t _ info (<

>),

( ,, ,
.). ,
.

trnpl

296

/.

Python 3

< > < >


. , u
. ,

"sqlite_",

. ,

SQL.

, u t :

sqlite> CREATE L tale (polel);


Error: near "t": syntax error
, :

sqlite> CREATE
sqlite> .taes
t
tmpl
tmp2

"tale"

(polel);

, :

sqlite> DROP L "tale";


sqlite> CREATE L [tale] (polel);
sqlite> .taes
t
tmpl
tmp2

SQL

n . SQL-

DROP

L <

> t . ,
~ u, u,

. SQL-

DROP

u, u.
u , , <

>, :

INTEGER-

"INT"
INT, INTEGER, TINYINT, SALLINT,

.
MEDIUINT, IGINT .;

- "R",
CARACTER(30), VARCAR(250),

VARYING

"CLOB" "". , ,
CLOB .

CARACTER(l00),

+
+
+

NONE-

REAL-
DOUBLE, DOUBLE PRECISION, FLOAT;
NUMERIC-

"BLOB"

"REAL", "FLOA"

"DOUB".

REAL,

!
. ,

INTEGER, .

. .

INTEGER

1.

SQLite

297

. ,

SQLite

( ), . ,

INTEGER,

. ,
.
, . .
:

sqlite> CREATE L tmp (pl INTEGER, 2 INTEGER,


... > INTEGER, 4 INTEGER, 5 INTEGER);
sqlite> INSERT INTO tmp VALUES "(10, "00547", 5. 45, "", NULL);
sqlite> SELECT * FROM tmp;
10154715.451l

sqlite> SELECT typeof(p1), typeof(p2), typeof(p3), typeof(p4),


... > typeof(p5) FRO tmp;
integerlintegerlrealltextlnull
sq1ite> DROP L tmp;

, .

SQLite

typeof () .Li.

~;~:

NULL- NULL;
;

INTEGER-

+
+
+

REAL- ;
- ;
BLOB- .

INTEGER PRIARY (. .

), NULL.

NULL

. :

sqlite> CREATE L tmp (1 INTEGER PRIARY );


sqlite> INSERT INTO tmp VALUE (10);

sqlite> INSERT INTO tmp VALUES (5.78); --


Error: datatype mismatch
sqlite> INSERT INTO tmp VALUES ("");'--
Error: datatype mismatch
sqlite> INSERT INTO tmp VALUES (NULL);
sqlite> SELECT * FRO tmp;
10
11

sqlite> DROP

L tmp;

NUERIC INTEGER.
S. ,

INTEGER,

. , , NUERIC,
:

INTEGER;

- REAL.

298

/.

Python 3

sqlite> CREATE

tmp3

(1 );

sqlite> INSERT INTO tmp3 VALUES ("00012.86");


sqlite> INSERT INTO tmp3 VALUES ("52.0");
FRO

sqlite> SELECT pl, typeof(p1)

tmp3;

00012.861text
52.01text
sqlite> SELECT CAST

(1

AS INTEGER)

FRO

tmp3;

(1

AS

FRO

tmp3;

12
52
sqlite> SELECT CAST

NUERIC)

12.86
52
sqlite> DROP

tmp3;

n <> r :

NOT NULL [< >] -

, n

n n. , n

NULL;

DEFAULT <>- n , n
, n n . :

sq1ite> CREATE

sqlite> INSERT INTO tmp3

tmp3
(1)

(1,

INTEGER DEFAULT 0);

VALUES (800);

sqlite> INSERT INTO tmp3 VALUES (5, 1204);


sq1ite> SELECT *

FRO

tmp3;

80010
511204
sqlite> DROP

L tmp;

n <> lt:

CURRENT_TIE-

CURRENT_DATE- UTC --;

URRN_IS-

UTC

::;

UTC

-- ::.

sqlite> CREATE

tmp3 (id INTEGER,

... > t

DEFAULT CURRENT_TIME,

... > d

DEFAULT CURRENT_DATE,

... > dt DEFAULT CURRENT_TIESTAP);


sq1ite> INSERT INTO tmp3 (id) VALUES (1);
sqlite> SELECT *

FRO

tmp3;

1101:30:1912011-04-3012011-04-30 01:30:19
sqlite> /*

sqlite> DROP

2011-04-30 05:30:19 */

tmp3;

COLLATE <>- .
INARY ( n. ), NOCASE ( ) RTRIM.

1.

299

SQLite

sqlite> CREATE
sqlite> INSERT INTO
sqlite> SELECT 1

(1, 2 COLLATE NOCASE);


VALUES ("abcd", "abcd");

L tmp
tmp

"D"

FRO tmp;

"D"

FRO tmp;

sqlite> SELECT

--

sqlite> DROP

L tmp;

t UNIQUE

NOCASE

[< >]

(<>)

, ,

10

20:

sqlite> CREATE L tmp3 (


... > 1 INTEGER CHECK(pl IN (10, 20)));
sqlite> INSERT INTO tmp VALUES (10);

sqlite> INSERT INTO tmp VALUES (30); --


Error: constraint failed
sqlite> DROP L tmp;

PRIARY

[ASC

1 DESC]

[<

>]

[AUTOINCREENT]- ,

NULL.

INTEGER,
NULL

. :

sqlite>
sqlite>
sqlite>
sqlite>

CREATE L tmp (id INTEGER PRIARY


INSERT INTO tmp VALUES (NULL, "1");
INSERT INTO tmp VALUES (NULL, "2");
SELECT * FROM tmp;

);

111

212

sq1ite> DELETE FRO tmp WHERE id=2;


sqlite> INSERT INTO tinp VALUES (NULL,
sqlite> SELECT * FROM tmp;

"");

111

213

sqlite> DROP

L tmp;

NULL,

. , ,

, .
, AUTOINCREENT. :

sqlite> CREATE L tmp (


... > id INTEGER PRIARY AUTOINCREENT,
... > t );

300

/.

Python 3

sqlite> INSERT INTO tmp VALUES (NULL, "l");


sqlite> INSERT INTO tmp VALUES (NULL, "2");
sqlite> SELECT * FRO tmp;
liCpoal
212

sqlite> DELETE FRO tmp WHERE id=2;


sqlite> INSERT INTO tmp VALUES (NULL,
sqlite> SELECT * FRO tmp;

"");

liCpoal

sqlite> DROP

tmp3;

n n. ,

2, n n. , n
.
n n , n n
n n n: ROWID, _ROWID_. :

sqlite>
sqli te>
sqlite>
sqlite>

CREATE L tmp (t );
INSERT INTO tmp VALUES ( "l") ;
INSERT INTO tmp VALUES ( "2");
SELECT ROWID, OID, _ROWID_, t FRO tmp3;

llllliCpoal

2121212

sqlite> DELETE FROM tmp WHERE OID=2;


sqlite> INSERT INTO tmp VALUES ( "");
sqlite> SELECT ROWID, OID, _ROWID_, t FRO tmp;
llllliCpoal

2121213

sqlite> DROP

tmp3;

n <~ >
:

PRIARY

(<

>)

[< ll>]

n n ;

UNIQUE (< >). [< ll>]- , t n ;

(<>) - .

n < ll>
n . :

ON CONFLICT

<>

n <> :

ROLLBACK- n n
, n n .
, n R;

R- n

, . , n
, .
;

R n

1.

FAIL-

301

SQLite

, ,

, R.

. ,
, ;

IGNORE-
;

REPLACE-

UNIQUE

. .

NOT NULL
NULL .

, R. ,

sqlite>
... >
sqlite>
sqlite>
sqlite>
101s2
sqlite>

16.3.

IGNORE.

UNIQUE:

CREATE L tmp (
id UNIQUE ON CONFLICT REPLACE, t );
INSERT INTO tmp VALUES (10, "sl");
INSERT INTO tmp VALUES (10, "s2");
SELECT * ~ tmp;
DROP

L tmp;

INSERT [OR
[ (<l>,

INTO [< >.]< ~>


... ) ] VALUES (<l>, <2>, ... ) ;

<>]
<2>,

. OR
R,

INSERT. :

FAIL, IGNORE

<> (ROLLBACK,

REPLACE).

. ,
,

VALUES.

. ,

INSERT

. , ,
n n

CREATE

L.

user ( ), rur ( ) site (

):

sqlite>
... >
... >
... >
sqlite>
... >
. . .>
sqlite>
... >
... >
... >

CREATE L user (
id user INTEGER PRIARY
email ,
passw );
CREATE L rur (
id rur INTEGER PRIARY
name_rur ); .
CREATE L site (
id site INTEGER PRIARY
id user INTEGER,
id rur INTEGER,

AUTOINCREENT,

AUTOINCREENT,

AUTOINCREMENT,

302

/.

Python 3

... > url ,


... > title ,
... > msg );

,
, .

site

,
, .
,
. .

SQLite.,

sqlite> INSERT INTO user (email, passw)


... > VALUES ('unicross@mail.ru', 'password1');
sqlite> INSERT INTO rur VALUES (NULL, '');
sqlite> SELECT * FROM user;
11unicross@mail.rulpassword1
sqlite> SELECT * FRO rur;
11

sq1ite> INSERT INTO site (id_user, ld rubr, url, tlt1e, msg)


... > VALUES (1, 1, 'http://wwwadmin.ru', '', '');

email

passw.

user

id_user ,
id_user

. ,

NULL. .
site. id_user id_rur
11 user rur. .

user rur. ,
. , Y'IWe .
(, )

SQL-.
, - .
r .

, .
:

sqlite> INSERT INTO rur VALUES (NULL,


Error: near "": syntax error

'

' N'

');

,
:

sqlite> INSERT INTO rur VALUES (NULL,


sqlite> INSERT INTO rur VALUES (NULL,
sqlite> SELECT * FRO rur;
11

21

' N'

'

N'

"

' N'");

'

'' N''

');

1.

303

SQLite

( UNIQUE ), SQL . ,

REPLACE

OR. 2:

sqlite> INSERT OR REPLACE INTO'rur


... > VALUES (2, '');
sqlite> SELECT * FRO rur;
11

21
I

' N'

REPLACE REPLACE INTO.

REPLACE INTO
[(<l>,

[< >.]<

<2>,

... )] VALUES

(<l>,

sqlite> REPLACE INTO rur VALUES (3,


sqlite> SELECT * FRO rur;

>
<2>,

... );

3:

'');

11

21
!

16.4.

UPDATE. :

UPDATE [OR <>] [< " >.]<


SET <l>='<>', <2>='<32>',
[WHERE <>];

>

OR <> (ROLLBAC,
FAIL, IGNORE REPLACE).
. SET

R,

. ,

WHERE. , <>,

. <>,
.

sqlite> UPDATE rur SET name_rur='o' WHERE


sqlite> SELECT * FROM rur;

3:

id_rur=;

11

21
I

DELETE
[WHERE

FRO

DELETE. :

[< >.]< >

<>];

304

/.

Python 3

, .
, .

3:

sqlite> DELETE FRO rur WHERE id


sqlite> SELECT * FRO rur;

rur=;

11

21

.
, SQL- VACUU.
, SQL-

(ROWID, OID _ROWID_).

16.5.

ALTER L. SQLite ALTER L

. ,

. ~:

ALTER L [< >.]< >


<>;

<> :

RENAE < >- .

user

sqlite>

users:

.taes

rur
sqlite_sequence tmpl
site
t
tmp2
sqlite> ALTER L user RENAE users;
sqlite> .taes
rur
sqlite_sequence tmpl
site
t
tmp2

user

users

ADD [COLUMN] < n> [<n >] [<n>] -

. ,
,

NULL , . .

. , PRIARY

UNIQUE.

iq

site:

sqlite> ALTER L site ADD COLUN iq INTEGER DEFAULT 0;


sqlite> PRAGA tae_info(site);
Olid_siteiiNTEGERIOI 11
llid_useriiNTEGERIOI 10
21id_ruriiNTEGERIOI 10
3 1ur 11 1 1 1
41tit~eiTEXTIOI 10
5 1msg 1 1 1 1
liqiiNTEGERIOIOIO

sqlite> SELECT *

FRO

site;

llllllhttp://wwwadmin.ruiHaaeiOncaeiO

16. SQLite

305

SQLite

3.1.3

VACUU.

16.6.

SELECT.

SELECT [ALL
[<

DISTINCT]

D.]<>[,

SQL-

>

[AS

... ]

... ] ]
WHERE <>.]
[ GROUP < > ] [ AVING <> ]
ORDER < > [COLLATE BINARY 1 NOCASE] [ASC 1 DESC] [, ... ] ]
LIMIT <> ]
FRO <

<>][,

SELECT ,
WHERE: WHERE ,

. rur:

sq1ite> SELECT

id_rur,

n rur

FRO rur;

11
21

sq1ite> SELECT

id_rur, n rur FRO rur

1:

WHERE id

rur=1;

11

*.

. rur:

sq1ite> SELECT *

FRO rur;

11
21

SQL- SELECT .
, :

sq1ite> SELECT 10 + 5;
15
,
,

sq1ite> SELECT (10 + 5) AS expr1,


151140

AS:

(70 * 2) AS expr2;

. site
rur:

sq1ite> SELECT s.ur1, r.nae_rur FRO site AS s,


... > WHERE s.id_rur = r.id_rur;
http://wwwadmin.ruipopapoae

rur

AS r

/.

Python 3

n n . n n n n n n n ,

n . n n 1
.

DISTINCT,

no

SELECT

ALL

DISTINCT.

ALL

, n.

nn .

GROUP n nn n.

n n n . n
:

sq1ite>
sq1ite>
... >
sq1ite>
... >

INSERT
INSERT
VALUES
INSERT
VALUES

INTO rur VALUES (3, ' n');


INTO site (id_user, id_rur, ur1, tit1e, msg, iq)
(1, 1, 'http://python.org', 'Python', '', 1000);
INTO site (id_user, id_rur, ur1, tit1e, msg, iq)
(1, 3, 'http://goog1e.ru', '', ", 3000);

n :

sq1ite> SELECT id_rur, COUNT(id_rur) FROM site


... > GROUP id rur;
112
311
nn n, n

AVING. n , WHERE,
nn . n ,

sq1ite> SELECT id_rur FROM site


... > 'GROUP id rur AVING COUNT(id_rur)>1;
1
n 1 n couN

(),

n. , ~:~n1 :

COUNT (<>

*) -

1 n.

sqlite> SELECT COUNT(*)

FRO

site;

MIN

(<>) - n.

sqlite> SELECT MIN(iq) FROM site;

(<>)

h.

sq1ite> SELECT
3000

AVG (<>)

AX(iq)

FRO

site;

- n.

1.

307

SQLite

sqlite> SELECT AVG(iq) FROM site;


1333.33333333333

su (<>)

sqlite> SELECT
4000

SU(iq)

FRO

site;

ORDER

ASC). DESC,
COLLATE

(INARY NOCASE). :

sqlite> SELECT *

FRO rur

ORDER

name

rur;

ORDER

name

rur

21
I
11

sqlite> SELECT *

FRO rur

DESC;

11

31
21

, , ,

LIMIT. , site

, ,

, ,

LIMIT
LIMIT
LIMIT

10 . :

<
<

>
>,

<

>

< >

OFFSET

<

>

. ,
.
. :

sqlite>
sqlite>
sqlite>
sqlite>
sqlite>
sqlite>
sqlite>

CREATE
INSERT
INSERT
INSERT
INSERT
INSERT
SELECT

tmp3 (id INTEGER);


INTO tmp3 VALUES(l);
INTO tmp3 VALUES(2);
INTO tmp3 VALUES(3);
INTO tmp3 VALUES(4);
INTO tmp3 VALUES (5);
* FRO tmp3 LIMIT 3; -- LIMIT

2
3
sqlite> SELECT * FRO tmp3 LIMIT 2, 3;
3
4
5
sqlite> SELECT * FROM tmp3 LIMIT 3 OFFSET 2;
3
4
5

sqlite> DROP

tmp3;

16.7.

/.

Python 3

SQL-

SELECT

FRO:

[AS <>]
[OUTER 1 INNER 1 CROSS] JOIN
< Q> [AS <>]
[ON <>] [USING ( <> ) ]
FRO <

, 1 [NATURAL]

l>

[LEF]

FROM,
WHERE , .

(
), .

Slte, e-mail,
:

sqlite> SELECT site.url, rur.name_rur, users.email


... > FRO rur, users, site
... > WHERE site.id rur=rur.id rur AND
... > site.id_user=users.id_user;
http://wwwadmin.ruipopapoaelunicross@mail.ru
http://python.orgipopapoaelunicross@mail.ru
http://google.ruiocoe opalunicross@mail.ru

. ;

, :

sqlite> SELECT url, name_rur, email


, .. > FRO rur AS r, users AS u, site AS s
... > WHERE s.id rur=r.id rur AND
... > s.id_user=u.id_user;

JOIN

INNER JOIN.

JOIN, : CROSS
JOIN:

sqlite> SELECT url, name_rur, email


... > FRO rur JOIN users JOIN site
... > WHERE site.id rur=rur.id rur AND
... > site.id- user=users.id- user;

WHERE ON, WHERE

. ,

sqlite>
... >
... >
... >
... >

1:

SELECT url, name_rur, email


FRO rur JOIN users JOIN site
ON site.id rur=rur.id rur AND
site.id user=users.id user
WHERE site.id_rur=l;

ON

USING:

sqlite> SELECT url, name_rur, email


... > FRO rur JOIN site USING (id_rubr) JOIN users USING (id_user);

1. SQLite

JOIN

309

, .

, ,

sq1ite> SELECT name_rur, COUNT(id site)


... > FRO rur JOIN site USING (id_rur)
... > GROUP rubr.id_rur;
12
11

"", . .
. ,
. :
<61>

ON

LEF

[OUTER] JOIN

<2>

<61>.<1>=<2>.<2>

1 USING

(<>)

, ,
<1>, <2> (

<62>

NULL). -

sqlite> SELECT name_rur, COUNT(id_site)


... > FRO rur LEF JOIN site USING (id_rubr)
... > GROUP rubr.id rur
... > ORDER rubr.name_rur;
i
11
12

16.8.

WHERE

WHERE AVING. ,
.
:

= == -

. :

sqlite> SELECT *

FRO rur

WHERE

id_rur=1;

11

sqlite> SELECT 10 = 10, 5 = 10, 10 == 10, 5


1101110

10;

,
AVING,

SELECT.

WHERE

-;

1 - ;

NULL.

COLLATE <>.

310
<>
( )

sq1ite> CREATE
sq1ite> INSERT INTO
sq1ite> SELECT 1

/.

Python 3

BINARY ( ), NOCASE

RTRIM. :
(1, 2 COLlATE NOCASE);
VALUES ("abcd", ."abcd");

L tmp
tmp

"D"

FRO tmp;

sq1ite> SELECT 2
"D"
1
sq1ite> DROP L tmp3;

FRO tmp;

sq1ite> SELECT 's' = 'S', 's' = 'S' COLlATE NOCASE;


011

NOCASE .

. :

sq1ite> SELECT
010

!=

<>-

''

'',

''

''

COLlATE NOCASE;

sq1ite> SELECT 10 != 10, 5 != 10, 10 <> 10, 5 <> 10;


0111011

+
+
+
+

<-;

IS NOT NULL, NOT NULL

+
+

rs NULL ISNULL-

>-;
<=- ;

>=- ;

BETWEEN

<>

AND

sq1ite> SELECT 100

NONULL- ;
;

<>- . :

BEWEEN

1 AND 100;

sq1ite> SELECT 101 BETWEEN 1 AND 100;

IN (< >) -

. :

sq1ite> SELECT
1
sq1ite> SELECT

''

IN

('',

'',

'');

''

IN

('',

'',

'');

LIE <>

[ESCAPE <>] -

%- ;

- .

" . ,
,

% :

16.

311

SQLite

sq1ite> SELECT 'test word test'

LIE

'%word%';

1
, :

sq1ite> SELECT 'test word test'


1
sqlite> SELECT 'test word test'

LIE

'test%';

LIE

'word%';

, :

sqlite> SELECT 'test word test'

LIE

'%es %wo d%';

LIE

'%wor%d%';

sq1ite> SELECT 'test word test'


1

. ,
% ,
.

, %

_?

. ,

sq1ite> SELECT '10$'


1
sqlite> SELECT '10$'

ESCAPE

<>:

LIE

'10%';

LIE

'10\%' ESCAPE 1\1;

LIE

'10\%' ESCAPE 1\1;

sq1ite> SELECT '10%'


1

,
. ,

true ( 1, yes, on) case_sensitive_like SQL- PRAGA. :


sq1ite> PRAGA case_sensitive_1ike
sq1ite> SELECT 's' LIE 'S';

true;

sq1ite> PRAGA case sensitive 1ike


sq1ite> SELECT 's' LIE 'S';

fa1se;

1
, :

sq1ite> SELECT

''

LIE

'',

''

LIE

'';

111
, .
, . :

sq1ite> SELECT

''

LIE

'',

''

LIE

'';

111
, "" "", "" "".
, , .

312

1.

Python 3

Widows-1251.
866, :

C:\book>chcp 866
:

866

C:\book>sq1ite3.exe testd.d
SQLite version 3.7.6
Enter ".he1p" for instructions
Enter SQL statements terminated with ";"
sq1ite> SELECT '' LIE '', '' LIKE '';
010
sq1ite> SELECT '' LIE '', '' LIE '';
011
. ,
.
PRAGA

encoding =

SQLite

UTF-8.

<> .

UTF-8, UTF-16, UTF-16\e

UTF-16be.

866 Widows-1251,
.

UTF-8

. , ,
.

UTF-8.
. n

sq1ite> SELECT 's' = 'S', NOT ( 's' = 'S');


011
sq1ite> SELECT NOT '' IN ('', '',

NOT.

:');

, ,
:

+
+

AND- ;

OR-

16.9.

.
, . "n
().
. , ,
. ,

,
.
, :

SELECT

< >

FROM

<>

WHERE

<>=<>;

16.

SQLite

+
+
+

313

SQLite

n ;
;
.

n .

CREATE

L n

PRIARY

n n n n n n.
n n n .

, n n n

, n SQL-

EXPLAIN [QUERY PLAN]


EXPLAIN. SQL-:

<SQL-anpoc>

QUERY PLAN

, n n n

. , n

. n nn n n n

site.

n n n n, n ,

- n:

sq1ite> EXPLAIN QUERY PLAN SELECT * FROM site WHERE id_site=1;


OIOIOISEARCH L site USING INTEGER PRIARY (rowid=?) (-1 rows)
sq1ite> EXPLAIN QUERY PLAN SELECT * FROM site WHERE id_rur=1;
OIOIOISCAN L site (-100000 rows)
n

"USING INTEGER PRIMARY

" , n n

n n , n.

n .

n . n

CREATE INDEX.

SQL-

CREATE [UNIQUE] INDEX [IF NOT EXISTS]


[< >.]< >

ON

<

>

(< n>

[ COLLATE

< >]

CREATE

INDEX

[ ASC

DESC] [, ... ])

UNIQUE,

. n n.

UNIQUE

, .

n . , n
, n ,

WHERE n

n :

WHERE

id_rur=<Hoep >

,
n n n SQL-

EXPLAIN, :

sq1ite> EXPLAIN QUERY PLAN SELECT * FRO site WHERE id rur=1;


OIOIOISCAN L site (-100000 rows)
sq1ite> CREATE INDEX index_rur ON site (id_rur);
sq1ite> EXPLAIN QUERY PLAN SELECT * FROM site WHERE id_rur=1;
OIOIOISEARCH L site USING INDEX index rur (id_rur=?) (-10 rows)

314

/.

Python 3

"USING INDEX
index_rubr". , ,

. ,

SQLite

, SQL-apoc :

sq1ite> SELECT *

FRO

site WHERE

id_rur=l;

1111llhttp://wwwadmin.ru1Haael0ncael0

2111llhttp://python.org1Pythonl 11000

REINDEX.

REINDEX

SQL-

[<

>.]< >

, .
.
SQL-

DROP INDEX.

DROP INDEX [IF EXISTS]

[<

>.]< >

, SQL- VACUU.

sqlite_statl.

.
, SQL-

ANALYZE ..

ANALYZE [ [<

>.

SQL-

] <

>]

ANALYZE sqlite_statl:

sqlite> SELECT * FRO sq1ite statl; --.


Error: no such tale: sq1ite_statl
sqlite> ANALYZE;
sqlite> SELECT * FRO sq1ite_stat1;
sitelindex_ruri 2

rurii

users 111

16.1 .

SELECT ,

.
:

CREATE

1 TEMPORARY]

[IF NOT EXISTS]


> AS < SELECT>;

[< >.]<

rur :

sq1ite> CREATE L tmp rur AS SELECT * FROM rubr;


sq1ite> SELECT * FRO tmp_rur;

1.

SQLite

315

11

21
I n

SELECT,

INSERT.

INSERT [OR
[ (<l>,

INTO [<
... ) ] <n SELECT>;

<>]
<2>,

~>.]< ~

tmp_rur,
:

sqlite> DELETE FROM tmp_rur;


sqlite> INSERT INTO tmp_rur SELECT * FROM rubr WHERE id
sqlite> SELECT * FRO tmp_rur;

rur<;

11

21

, <>,

. ROLLACK, R,

FAIL, IGNORE

REPLACE

, .

REPLACE-

IGNORE

IN.

WHERE.

"r":

sqlite> SELECT * FROM site WHERE id rur IN (


... > SE~ECT id_rur FRO rur
... > WHERE nm_rur='');
llllllhttp://wwwadmin.ruiHaaeiOncaeiO

21llllhttp://python.org1Pythonl 11000

16.11.

. ,

. ,
, .
, .
.

, n,
i.

SQLite

, ,

, .
.

BEGIN [DEFERRED 1

BEGIN.

IEDIATE

1 EXCLUSIVE] [TRANSACTION];

316

/. Python 3

n r

END.

. -

[TRANSACTION];
END [TRANSACTION];

, n , n

ROLLBAC. :

ROLLBACK [TRANSACTION]

[SAVEPOINT]

< >);

n n ; n, n

sqlite>
sqlite>
sqlite>
sqlite>
sqlite>

BEGIN TRANSACTION;
INSERT INTO rur VALUES (NULL, '');
INSERT INTO rur VALUES (NULL, '');
ROLLBACK TRANSACTION; --
SELECT * FRO rur;

li

21
I n

, n .
n ,
n.

, n

, ON CONFLICT <> n

OR <> n n.

n R. n
, n ,
. , n ,
. n nn n. n
, :

sqlite> BEGIN TRANSACTION;


sqlite> INSERT INTO rur VALUES (NULL, '');
sqlite> INSERT INTO rur VALUES (3, ''); --
Error: PRIARY must unique
sqlite> I TRANSACTION;
sqlite> SELECT * FROM rur;
li

21
I n

41

n, n n n .
, n ROLLBAC.

n
n, n n .
n:

sqlite> BEGIN TRANSACTION;


sqlite> INSERT OR ROLLBACK INTO rubr VALUES (NULL,

'');

1.

317

SQLite

sqlite> INSERT OR ROLLACK INTO rubr VALUES (3, '');


Error: PRIARY must unique
sqlite> I TRANSACTION; -- !
Error: cannot commit - no transaction is active
sqlite> SELECT * FROM rur;
11

21
I

41

SAVEPOINT

<

BEGIN
SAVEPOINT. :

>;

RELEASE.

RELEASE [SAVEPOINT]

< >;

, , ROLLAC.
, ,
:

sqlite>
sqlite>
sqlite>
sqlite>
sqlite>

SAVEPOINT metkal;
INSERT INTO rur VALUES (NULL,
INSERT INTO rur VALUES (NULL,
ROLLBACK SAVEPOINT metkal;
SELECT * FROM rur;

'');
'');

11

21
I

41

16.12. _

DROP L. ,

. , , .
:

DROP

[IF EXISTS]

SQLite

[< ~>.]< v;

. , .

- SQLite.
,

SQLite.

17

SQLite

Python

SQLite

Python.

sqlite3,

SQLite. sqlite3
2.5,

Python,

Python

Python,
DB-API (DataBase Application Program lnterface).

, ,

2.0

249,

DB-API

http://www.python.org/

dev /peps/pep-0249.

sqlite3

DB-API 2.0,

. , ,

DB-API 2.0

. ,
,

>>> import sqlite3


>>> sqlite3.apilevel
'2.0'

#
#

apilevel:

sqlite3
sqlite_version sqlite_version_info. sqlite_version
, sqlite_version_info . :

>>> sqlite3.sqlite_version
'3.7.4'
>>> sqlite3.sqlite_version_info
(3, 7' 4)

DB-API 2.0

1.

connect ().

,
.

2.

-.

3.

17.

SQLite

Pytho

319

n SQL-anpoc . n n

n. n (INSERT, REPIACE, UPDATE DELETE),


n .

4.

5.
6.

-.
.

17.1.

connect ().

connect(database[, timeout] [, lsolatlon_level] [, detect types]


[, factory] [, check_same_thread] [, cached_statements])
n

database n .

, .
, n .
n

:memory:,

n n. .
n n
n

n.

timeout .
n timeout n . n
n.

connect () , n

. ,

. ,
. n

close ()

testdb.db,

>>> import
>>> con
>>>

sqlite

= sqlite

..connect

("testd.d")

>>> con. close ()

17 .2.

#
#
#
#

sqlite

rn ~
~
rn ~

DB-API 2.0

-. n n .

- n n cursor (). n
n n -:

+
+

close ()

- -;

executescript (<SQL-anpoc >)- n SQLanpoco . n n n ,

. n :

320

/.

Python 3

# -*- coding: utf-8 -*import sqlite


con
sqlite.connect ("catalog.d")
cur = con. cursor ()
# -
sql = """\
CREATE L user (
id user INTEGER PRIARY AUOINCREENT,
email ,
passw
);

CREATE L rur
id .rur INTEGER
name rur

PRIARY AUTOINCREENT,

);

CREATE L site
id site INTEGER PRIARY
id_user INTEGER,
id_rur INTEGER,
url ,
title ,
msg ,
iq INTEGER

AUTOINCREENT,

) ;

try:

#
cur.executescript(sql) #n SQL-anpoc
except sqlite.DatabaseError as err:
print (":", err)
else:
print (" ")
cur, close ()
# -
con. close ( )
#
input ()
,

. , UTF-8.
SQLite;

+ .execute ( <SQL-apoc> [,

<> J)

SQL-apoc.

, .
n

user:

# -*- coding: utf-8 -*import sqlite


con
sqlite.connect("catalog.d")
cur = con. cursor ( )
# -
sql = """\
INSERT INTO user (email, passw)
VALUES ('unicross@mail.ru', 'passwordl')

17.

SQLite

321

Python

try:
cur.execute(sql)
# n
except sqlite.DatabaseError as err:
print (":", err)
else:
print (" m")
con . ni t ( )
#
cur. close ( )
#
con. close ()
#
input ()

SQL-apoc

ni t

()

. ni t

()

, .
,

.
, t, ,

(INSER'I', REPLACE, UPDAE DELETE), conit ().

SQL-apoc J:!,
. SQL-apoc,

, ,
. ,

execute (). SQL-

apoce :

- ;

: <> -

# -*- coding: utf-8 -*import sqlite


con = sqlite.connect("catalog.d")
cur = con.cursor()
#
tl
("",)
t2 = (2, "")
d

{"id": 3,

"n":

"""'"

""''}

sql_tl
"INSERT INTO rur (n_rur) VALUES (?) ..
sql_t2
"INSERT INTO rur VALUES (?, ?) "
sql_d
"INSERT INTO rur VALUES ( :id, :n)"
try:
cur.execute(sql _tl, tl)
# 1-
cur.execute(sql_t2, t2)
# 2-
cur.execute(sql_d, d)
#
except sqlite.DatabaseError as err:
print (":", err)
else:
print("apoc n")

con. ni t ()
cur.closej)
con. close ( )
input ()
11

1349

#
#
#

322

/.

Python 3

t1.
. , 1
. , .
. ,

.
narne d
. ,

, .
!
SQL-apoc , .
.

execute ( )

executernany () .

executernany(<SQL-apoc>,

<>)- SQL-apoc

, .
(

"?")

( ":<>").
- -.
, ; site

executemany ( ) :

# -*- coding: utf-8 -*import sqlite3


con
sqli te3. connect ( "catalog. d")
cur
con. cursor ( )
# -
arr
(1, 1, "http://wwwadmin.ru", "", "", 100),
(1, 1, "http://python.org", "Python", '"', 1000),
(1, 3, "http://google.ru", "", "", 3000)
sql = """\
INSERT INTO site (id_user,
VALUES (?, ? , ? , ? , ? , ? )

id_rur,

url, title, msg, iq)

try:
cur.executernany(sql, arr)
except sqlite3.DatabaseError as err:
print (":", err)
else:
print (" m")
con. commi t ()
#
cur. close ( )
#
con. close ( )
#
input ()

sqli te3 execute (), executernany () executescript ()


, -.


3 {

DB-API 2.0.
17.1 ).

17.

SQLite

323

Pytho

# -*- codlng: utf-8 -*import sqlite3


con = sqlite.connect("catalog.d")
try:
con.execute("""UPDATE rubr SET n rur=' '
WHERE id_rur=""")
except sqlite.DatabaseError as err:
print ("!1: ", err)
else:
con. commi t ()
#
print! " m")
con. close 1)
#
input ()
- n :

lastrowid- n n INSER
execute (). , None.

n :

# -*- coding: \ltf-8 -*import sqlite3


con
sqlite.connect("catalog.d")
cur = con. cursor ()
# -
try:
cur.execute("""INSERT INTO rur (name_rur)
VALUES ('.')""")
except sqlite.DatabaseError as err:
print ( "011: ", err)
else:
con.commit ()
#
print (" m")
rint(":", cur.lastrowid)
cur. close ()
# -
con. close ( 1
# i,J
input ( 1

rowcount-

n. n

. -1;

description- n
SELECT.

n,

None.
SELECT * F'ROM rubr,

n, n SQL-anpoc

(('id_rubr', None, None, None, None, None, None),


('name rur', None, None, None, None, None, None))

324

17.3.

/.

Python 3

n -:

n n n

fetchone () -

, n. n ,

None. n user:

import sqlite
con = sqlite.connect("catalog.d")
cur = con.cursor()
cur.execute("SELECT * FRO user")
<sqlite.Cursor object at 0150>
>>> cur.fetchone()
(1, 'unicross@mail.ru', 'password1')
>>> print(cur.fetchone())
None
>>>
>>>
>>>
>>>

_next_()- n n n
, n n. ,
Stoprteration. user
n

next () :

>>> cur. execute ( "SELECT * FRO user")


<sqlite.Cursor object at 0150>
>>> cur. next ()
(1, 'unicross@mail.ru', 'passwordl')
>>> cur. next
()

Stoplteration
for

next _ () .

n n - n .
n rur:

>>> cur.execute("SELECT * FRO rur")


<sqlite.Cursor object at Ox0150E2FO>
>>> for id_rur, n in cur: print ("{0) 1 {1}" .format

(id_rur,

n))

11
21

3 1
41

.,r

fetchmany ( [size=cursor .arraysize]) -

n n n

, n.

n . , ,

n n arraysize -.
n n
n, n
n. n , n n. :

>>> cur. execute ( "SELECT *


<sqlite.Cursor object at

FRO rur")

0150>

17.

SQLite

325

Python

>>> cur.arraysize
1

>>> cur.fetchmany()
[ (1, '')]
>>> cur.fetchmany(2)
[ ( 2, '' ) , ( 3, '
>>> cur.fetchmany(3)
[ ( 4 , ' ' ) ]
>>> cur.fetchmany()

'

)]

[]

fetchall 11 -

( )

. . .
. :

>>> cur.execute("SELECT * FROM rur")


<sqlite3.Cursor object at 01503>
>>> cur.fetchall()
[(1, ''), (2, ''),
( 4 , ' ' ) ]
>>> cur.fetchall()

(3,

'

'),

[]

>>> con. close ()


.
, ~. ,

row_ factory

, :

def

< >(<->,

<>):

#
return < >

user

# -*- coding: utf-8 -*import sql i te3


def my_factory(c, r):
d

{}

for i, n in enumerate(c.description):
d[name[O]] ~ r[i] #
d[i] ~ r[i]
#
return d
con ~ sqlite3.conect("catalog.d")
con.row_factory ~ my_factory
cur ~ . cursor ()
#
cur. execute ( "SELECT * FROM user" 1
arr ~ cur.fetchall()

17.2).

326

/.

Python 3

print (arr)
# :
"""[{0: 1, 1: 'unicross@mail.ru', 2: 'passwordl', 'id user': 1,
'passw' : 'passwordl', 'email' : 'unicross@mail. ru' } ] """
print (arr[O] [1])
#
print (arr[O] ["email"])
#
cur. close ()
# -
con. close ()
#
input ()
u

my_factory () . ,
row_factory

u u

. , u .

row_factory

Row

keys (),

.. :.....................................

: .:

... ' .

; ,.. : .... ,,,, ...

Row

u,

sqlite.

Row

17.3).

i ....,........... :, ::: ...,

;~;;;,,,,,,,.,;

.............. ;.

# -*- coding: utf-8 -*import sqlite


con = sqlite.connect("catalog.d")
con.row_factory = sqlite.Row
cur = con.cursor()
cur. execute ( "SELECT * FROM user")
arr = cur.fetchall()
print(type(arr[O]))
# <class 'sqlite.Row'>
print(len(arr[O]))
# 3
print (arr[O] [1])
#
print (arr [0] [ "email"])
#
print(arr[O] ["EAIL"])
#
for elem in arr[O]:
print(elem)
print(arr[O] .keys())
# ['id_user', 'email', 'passw']
cur. close ()
# -
con. close ()
#
input ()
, ,
. 1

Windows-1251.

SQLite ,
testdb.db

u :

>>> con = sqlite.connect ("testd.d")


>>> cur = con.cursor()
>>> cur. execute ( "SELECT * FROM rur")
...
sqlite.OperationalError: Could not decode to UTF-8 column
>>> con. close ()

'n

rubr'

17.

UTF-8.

SQLite

Pytho

327


11

text _ factory

OperationalError.

,
. , ,

bytes 1)

17 .4) .

..... ,......... " ..... ' ......... " ............. " ... ,............................. ,.......... , .............. : ...,.. ., ...... :,., ..... ,.,,.., .... ,.. ,. .............. ,.,........ ...................................... ,............ ,........ ,.. : ................. ,.......

"'"~

~ 17.4. ~t. i:tqxy

~............................. ;."''"'""'''"'"'''""'''"'";;,;;:. ~;.;::-;::,.;,,,:,; .........'...... .- ; ........... ;,;. ;~;.~.;-:i.;; : .............. ;........=;,; ........... ;;,,,,;;,;.. ;,,,;;,,;.:.=,;-.....=.: .........;.............;................. ;, ...................... : ;

>
>
>>>
>

con = sqlite.connect l"testd.d")


con.text factory = bytes # !
cur = con.cursorl)
cur. execute 1"SELECT * FROM rur")
<sqlite.Cursor object at Ox014FE380>
>>> cur.fetchonel)
11, b'\xcf\xf0\xee\xe3\xf0\xe0\xec\xec\xe8\xf0\xee\xe2\xe0\xed\xe8\xe5')

str 1) .

.
(

17.5).

!''J1~~~~~1r:s~y~~~~~~~~-~~~~~~f~~~~~~~y~;4~~:ri~~~;~~J~~~

. . . . . . ,. .,.c..,.,".,,", .."" . . . .-........... .

::.. ;.. '' ... '.... ': .. '...... '' ... '...... '...... '.. '.. '.. '.. ;, ': ... ; .-:'' ''" .. '.' ';;: ..... ;;........ ';' ;; ....;:.. >..... '' ... '.. :.'i "'" : :. ;... :" ... ; ;;, ...: i;. ;, ;... ',; . ';. ~ ... ;;.... ' ....... ;...... ;.

>>> con.text factory = lamda s: strls,


>>> cur. execute 1"SELECT * FROM rur")
<sqlite.Cursor object at Ox014FE380>
>>> cur.fetchonel)
11, '')
>>> con. c1ose 1)

17.4.

...................:.!

1 ...... ' '

"1251")

.
,
counit

1)

(INSERT, REPIACE, UPDATE

DELETE),

, .

CREATE

L,

VACUUM

. .

rollback 1)

. ,
(

17.6) .

......~ ........ ; ...................................................................... ~ .....~.; ............. y...............................................i ..............y ;y ........ ;;,.... y...........; ... ,; ... y............. ; ............... ~; ............................ y.,;, .. , :

>>> con = sqllte.connectl"catalog.d")


>>> cur = con.cursorl)
>>> cur. execute 1"INSERT INTO user VALUES INULL, 'user@mail. ru',

' ' ) ")

328
<sqlite.Cursor object at 01508>
>>> con.rollback()
>>> cur. execute ( "SELECT * fROM user")
<sqlite.Cursor object at 01508>
>>> cur.fetchall(f
[ ( 1, 'unicross@mail. ru', 'passwordl') ]
>>> con. close ()

/.

Python 3

n n

isolation_level connect (),


isolation_level . n :
"DEFERRED", "IEDIATE", "EXCLUSIVE", n None. n
BEGIN. None, n
. commit ().
n

. n n
n

isolation_level, n, n

n (

17.7).

>>> con = sqlite.connect("catalog.d", isolation_level=None)


>>> cur = con.cursor()
>>> cur. execute ( "INSERT INTO user VALUES (NULL, 'user@mall. ru', ' ' ) ")
<sqlite.Cursor object at 01508>
>>> con.close()
>>> con = sqlite.connect("catalog.d")
>>> con.isolation level
None #
>>> cur = con.cursor()
>>> cur.execute("SELECT * fROM user")
<sqlite.Cursor obJect at 01508530>
>>> cur.fetchall()
[(1, 'unicross@mail.ru', 'passwordl'), (2, 'user@mail.ru', ")]
>>> con.close()

17.5.

ORDER

n, "!", "2" "",


n n ("2", "" "\").
sqlite n n
SQL-anpoce.

ORDER

COLLATE.

SQL-anpoce n n n

create_collation () . :

create_collation(<Haae
<

SQL-apoce

>)

>,

17.

SQLite

Python

329

+
+
+

1 - n ;
- 1 - ;
- .

,
. .
, ,


( 17 .8).

# -- coding: utf-8 -*import sq1ite3


def myfunc (s1, s2): #
s1 = s1.1ower()
s2 = s2 .1ower ()
if s1 == s2:
return
elif s1 > s2:
return 1
else:
return -1

'

con = sqlite.connect(":memory:", isolation_level=None)


# "myfunc" myfunc()
con.create collatlon("myfunc", myfunc)
cur = con.cursor()
cur. ~xecute ( "CREATE L words (word ) ")
cur.execute("INSERT INTO words VLUS('l')")
cur.execute("INSERT INTO words VLUS('')")
cur.execute("INSERT INTO words VLUS('2')")
#
cur.execute("SELECT * FROM words ORDER word")
for line in cur:
print(line[O], end=" ") # : 2 l
print ()
#
cur.exocute("""SELECT * FROM words
ORDER word COLLATE myfunc""")
for llne in cur:
print(line[O], end=" ") # : l 2
cur. close ()
con. close ()
input ()

330

17.6.

1.

Python 3

LIKE

cur.execute("SELECT ''
print (cur. fetchone () [ 0] )
cur.execute("SELECT ''
print(cur.fetchone() [0])

''")

#
LIE

( )

( )

''")

#:


.
.

SQLite UPPER ()

sq1ite3

LOWER ()

SQL-apoce. ,
,
SQL-apoce.

SQL-apoce

create

create_function ()

functlon(<Haae

. :

<

SQL-apoce

>,

<m

>,

>)

. ,
, .

. ,

str.

. 11
(
~n~~~~~~,~:;-;;~:'~~~-~~-~~~~-:~~Ji~:~'~$;;~~,

17.9).

. . .,. . . . . . . . . . . . . . . .,_. . . . . ,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .:

.................................................... ............... .............................. .... ........ ........................................................................................................................................................ .................. :

# -*import sq1ite3

coding: utf-8 -*-

#
def myfunc(s):
return s .1ower ()

con = sq1ite3.connect ("cata1og.d")


# "my1ower" myfunc()
con.create_function("my1ower", 1, myfunc)
cur = con.cursor()
string = "%'~"
#
#
sq1 = """SELECT * FROM rubr
WHERE my1ower(name rur) LIKE ?"""
cur.execute (sq1, (string.1ower (),))
pr int (cur. fetchone () [ 1] )
#
cur. c1ose ()
con. c1ose ()
input ()

17.

SQLite

331

Python

, string .
, execute ()
. SQL-apoce,

.
create_function () u
. u. ,

SQLite

. , ,
, , .

u
(

17.1 0).

''''"''''':'"''''''"''''"'''0'0~'11''''1''''''"100\'lt''<111.''"'"'"'''1'''!0'"1'''".1''"'''''''':.'.''~1"'"''~''.10J:.'.'!.'''tnMt>.<<l0'"10'.''0<_."11''.''':"''":ooo:".'''"

[.. 11.10. ():).,~t!~liJ~~"'

:. "' :. '., :. 1" ,, ; '" 1"'' 1.: ' .. ' 11." ..... '. i;.; .=..: ....... ;, .;'1'. ,,;:;: .:

'i: .. '.. ;; 1; :.:: :.;; ,; . ;.. ".....:;,,; ;;, ;;~.';!';

: .
,; ...... ;;.,,,;.'": ,; 1:. ;;i; i.' ,:.;' ;; '; ' .. ;;.. '
~:

.:'.'''''?::::'''')'.''''""'!'''''":''~''''

'''''""''"':

'

i .'.,; ;, . ; :. : ;, : ' :: ;,, .. 1" ........ ' ... "

.......... :

# -*- coding: utf-8 -*-

1mport sqlite3
import tlme
def myfunc (d) :
return time.strftime("%d.%m.%Y", time.1ocaltime(d))
con = sq1ite3.connect(":memory:")
# "mytime" myfunc()
con.create_function ("mytime", 1, myfunc)
cur = . cursor ()
cur. execute ( "SELECT mytime ( 1303520699) ")
print \ cur. fetchone () [] ) # : 23.04. 2011
cur. c1ose ()
con. c1ose ()
put()

17.7.

SQLite
().

(), AVG () su

u COUNT (), MIN (),


u ,

. u
apoce

SQL-

create_aggregate ()

. :
create_aggregate(<Haae
<

SQL-anpoce

>,

<m

>,

>)

u .
( ).
:

step () fina1ize (). step ()

create_aggregate (). fina1ize () .


(
17.11).

332
"''~":"''''~::."".

/.

Python 3

.... ~.'"~,~~,,:::"~:~.:~:"'':'.''"''::"''""'""'~'".'":0".'''"""''''"'"''"''''''"''''"""'"""'"'''"'""'''"''''''""''''''''"''''''':"'''"''''0000 .. 000 .. 000 .. 00

j 1711; arperaro l-1

..

i ......." ................................. " ... ,",,,,";,:,;....~....", ...,. ........~ ... ;,;;;;,,.,,;;:"; ...;,;;.. ;, .. ~; ...... ~ . ~; .............: ......c.-.; .. ,. ... ,..........~ .... ,.... ,"........................... "......................................................................... ""''''''i

# -*- coding: utf-8 -*import sqlite3


class MyClass:
def
init (self) :
self. result = []
def step(self, value):
self.result.append(value)
def finalize(self):
self.result.sort()
return " - ".join(self.result)
con = sqlite.connect ("catalog.d")
# "myfunc" MyClass
con.create_aggregate("r_nyfunc", 1, MyClass)
cur = con.cursor()
cur. execute ( "SELECT myfunc (n rubr) FROM rubr")
print(cur.fetchone() [0])
# : - ~ - cur. close ()
con. close ()
input ()

17 .8.
SQLite

+
+
+
+

NULL-

INTEGERREAL-

NULL.

sqli t

None

Python;

float;

- .

UTF-8.

int;

SQLite

Python:

str. ,

text _ factory;

BLOB- . bytes.

, ,

SQLite,

register _ adapter ()

SQL-apoc.

:
register_adapter(<T ~ >,

<m

>)

.
, .
, , -

17.

SQLite

Pytho

333

SQLite.
17 .12).

~'".'"'""''"''"'"""'''"'"''"~"''""''"'''~"'"''""""''''"''''""''"'"''''''"''"""''"''''~''"~'-'''"""""''"''"""''"'"'""''""""''"''"'~.'''""'""'"""""""''""'"'"'"'""''"''""'"'"'"'"'"""''"''''"''''""'""'""''"'''"":

! 1112. ~ atpffl)a
..,ac~a
1.;."'.:: .;. ,,;;,,; .'.. ;,'
~ .. ;;; .. " " ' ,, ' ' " " ' ; 1 :. ' ' ;, ' ; ; . ,; . : 1" ;;, ; ,.; ; ; .... " . : ',;:. 1'.;.

. ..... ..

1 ;., ; 1 ;; . . . . . . , ; , '; 1 1 . . . ' ' , ; , ; , ; ' ; ; , , ;, .... ' ........ : ;, .. : :. , ; , ; : : .

:. ; . . . . . . . . . . . . ;, ; ; 1 '1

i' ... 1 ' ~

# -*- coding: utf-8 -*import sqlite

class Car:
def
init (self, model, color):
self.model, self.color = model, color
def my_adapter(car):
return "(0} 1 (l}".format(car.model, car.color)
#

my_adapter)
# Car
car
r("-2109", "")
con = sqlite.connect("catalog.d")
cur = con.cursor()
try:
cur.execute("CREATE L carsl (model
cur.execute ("INSERT INTO carsl VALUES
except sqlite.DatabaseError as err:
prijlt ( ": ", err)
else:
print (" m")
con. couni t ( )
cur. close ()
con. close ()
input ()
sqlite.regis~er_adapter(Car,

)")

(?) ",

(car,))

_ conform_ () .
conform

(self,

<>)

<>

PrepareProtocol.
246. ,
, SQLite. cars2
, _conform_ () ( 17.13).

# -*- coding: utf-8 -*import sqlite

class Car:
def
init (self, model, color):
self.model, self.color = model, color

334
def

/.

Python 3

conform (self, protocol):


if protocol is sqlite.PrepareProtocol:
return "{0) 1 {l}".format(car.model, car.color)

# Car
car
r("-412", "")
con = sql i t. connect ( "catalog. d")
cur = con.cursor()
try:
cur.execute("CREATE L cars2 (model mycar)")
cur.execute("INSERT INTO cars2 VALUES (?)", (car,))
except sqlite.DatabaseError as err:
rint(":", err)
else:
print ("n n m")
con.commit ()
cur. close ( 1
con. close ()
input ()
, n n

SQLite

Python

register_converter().

:
register_converter(<Tn ~>,

<m

>)

n n n n .
n , n n
n . n n n
.

n n, n

n ,

detect _types

connect ( 1.

n n

CREATE TABLE.

'"".'"'~~""'"''"'

....

~~t."~: ~

model:

no

, n

mycar

.._.~: ... ~""''~"."'""~'"""~ ~....'~":'""""'"". '"!

carsl

~:: "!"~:~ ~"':"'":'"!'""""''''~"~""'':!!-'~"'"

~;;,,;,,

sqlite,

model:

17.14) .

... ""''!!'"'" .......................... " .... "' ...................... '" ":

(r 17.~~()~~~~~~~t._~$
:......................... ;,,,,.,,,.,, ;... ;;;,,:,,,,:;;,,,,,;;,,,,,,,,,,,,,,,,.,,,,,,,,,.;,, .......................
............. ,,,,,;.. ;,.....................................:..... ;............... ..........................
# -*- coding: utf-8 -*import

cars2 (model mycar)


."-'""

mycar

n
L

[mycar]" F'ROM carsl

sqli t. PARSE_DECLTYPESCREATE

n SQL-anpoce n n

. n
"

1):

sqli t. PARSE _ COLNAESSELECT model as

n (

sys

class Car:
def
init (self, model, color):
self.model, self.color = model, color

........... ,...........

17.

def __repr __ (self):


s =": {0),
return s

SQLite

Pytho

335

{l)".forrnat(self.model, self.color)

def my_converter(value):
va1ue = str (val\.Je, "utf-8")
model, color = va1ue.sp1it("l")
return Car(model, co1or)

sq1i t. register_ converter ( "mycar",


con = sq1i t. connect ( "cata1og .d",

_converter)

detect_types=sqlite.PARSE_COLNAES)

cur = con. cursor ( )


cur. execute ( '""'SELECT model as
print (cur. fetchone () [] )
# : : -2109,
con. c1ose ()
input ()

"

[mycar]" FROM cars1""")

cars2

17.15).

-*- coding: utf-8 -*import sq1ite3, sys


c1ass Car:
def
init (se1f, model, color):
se1f.mode1, se1f.color = model, color
def
repr __ (se1f):
s =": {0), : {l)".forrnat(self.model, self.color)
return s
def my_converter(value):
value = str (value, "utf-8")
model, color = value.sp1it("l")
return Car(mode1, color)
# n n
sq1ite3. register_converter ( "mycar", my_converter)
con = sqlite.connect("catalog.d",
detect_types=sqlite.PARSE_DECLTYPES)

cur = con.cursor()
cur.execute("SELECT model FROM cars2")
print(cur.fetchone() [0])
# : : -412, :
con. close r)
input ()

336

17.9.

1.

Python 3

SQLite

( .
) . n

. n , ,
(

17.16).

# -*- coding: utf-8 -*import sq1ite3, datetime, time


#
def my_adapter(t):
return time.mktime(t.timetup1e())
#
def my_converter(t):
return datetime.datetime.fromtimestamp(f1oat(t))
#
sq1ite3.register_adapter(datetime.datetime, my_adapter)
sq1ite3. register_converter ( "mytime", my_converter)
#
dt = datetime.datetime.today()
con
sq1ite3.connect(":memory:", iso1ation_1eve1=None,
detect_types=sq1ite3.PARSE_COLNAES)

cur = con.cursor()
cur.execute("CREATE L times (time)")
cur.execute("INSERT INTO times VALUES (?)", (dt,))
cur.execute("""SELECT time as "t [mytime]" FROM times""")
print(cur.fetchone()[O]) # 2011-05-0114:38:14
con.c1ose()
input ()

sq1ite3

datetime .datetime-

datetime datetime
datetime .date date,
timestamp. , n
date

. n

17.17.

# -*- coding: utf-8 -*import sq1ite3, datetime


#
d = datetime.date.today()
dt = datetime.datetime.today()

17. i SQLite Pytho

337

con = sq1ite3.connect(":memory:", iso1ation_1eve1=None,


detect_types=sq1ite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("CREATE L times (d date, dt timestamp) ")
cur .execute ("INSERT INTO times VALUES (?, ?) ", (d, dt))
cur.execute("SELECT d, dt FRO times")
res = cur.fetchone()
print(res[O]) # 2011-05-01
print(res[1]) # 2011-05-01 14:40:28.562000
con. close ( )
input ()

17.10.

sqlite :

Exception
Warning
Error
InterfaceError
DatabaseError
DataError
OperationalError
IntegrityError
InternalError
ProgrammingError
NotSupportedError

Exception. -

sqlite.

except
sqlite.

+
+
+

(,

DatabaseError). :

warning- ;
Error- ,
. except, :
InterfaceError- , ,
;

+
+
+

DatabaseError- , ;
DataError- , ;
OperationalError- ,
, , SQL-apoce,

INSERT, . .

SQL-apoca;

+
+

Integri tyError- ;
InternalError- ;

338

Progra=ingError-

/.

Python 3

r. ,

execute (),

SQL-apoce;

NotSupportedError-

, .

r,
SQL- ( 17.18).
''""""'"'""'""""""'""'""''''"""'""'""""""''"'"'"''"'''"''"''"'''"'""'""""'""'"'""'"''"' ,.. ,"

........."'""'"'"""'"'""''"''"''"""'"""'"'"''" '" ... ,., ,.. ", .... ,........

1. ~-~~-~-~:.~.!:~~::,.~-~~~,~-~~-~~~~~9.~~:~~~.:~,~~~~-~~~.~~. ~.~~~:~~'~'''"";,;. , ,; , ,; . . . . . . . . . . . . . . . . . .:. . . . .

i :. ;;

# -*- coding: utf-8 -*import sqlite3, sys, re


def

d_connect(d_name):

try:
d = sqlite3.connect(d_name, isolation level=None)
except (sqlite3.Error, sqlite3.Warning) as err:
print (" . ")
input ()
sys.exit(O)
return d
rint("
d_name

:",

end=" ")

= input()
= d_name.rstrip("\r")

# 3.2.0 (. . 1.7)
con
d_connect(d_name)
#
cur = con.cursor()
sql = ""
print (" m n, <Q>+<Enter>")
while True:
tmp = input ( )
tmp = tmp.rstrip("\r")
# 3.2.0 (. . 1.7}
if tmp in ["q", "Q"]:
break
if tmp.strip() == "":
continue
sql = "(0} (l}".format(sql, tmp)
if sqlite3.complete_statement(sql):
try:
sql = sql.strip()
cur.execute(sql)
if re.match("SELECT " sql, re.I):
print(cur.fetchall())
except (sqlite3.Error, sqlite3.Warning) as err:
rint(":", err)
else:
print (" n m")
sql
cur. close ()
con. close ()

d_name

SQL-apoc ,

complete_statement (<SQL-anpoc>).

17.

True,

SQLite

339

Python

n n SQL-anpoco.

n n. n n

SQL-

anpoca n. n :

>>> sql = "SELECT 10 > 5;"


>>> sqlite3.complete statementlsql)

True
>>> sql = "SELECT 10 > 5"
>>> sqlite3.complete statementlsql)

False
>>> sql = "SELECT 10 > 5; SELECT 20 +
>>> sqllte3.complete statementlsql)

True

2.6,

Python

n n .

n n , n

.
n.

with

sqlite3

n ,

commit 1). n n
rollback 1). n rubr. n

n , n n, n

17.19).

r:~:~~i~~?::~r.:.i:~~~~~~~~:~~8;::~::~~~;:~::::~::::::::;::~:~:::~fi~1'o1i:;:;;;;:~r:;~;:::i::::::::;:::,::::;:::;::::::::::::::::::::::::::::::~:::::::::.::::::::!:::~:::::!:::::::::::;:::::
# -*- coding: utf-8 -*import sqlite3
con = sqlite3.connectlr"C:\book\catalog.d")
try:
with con:
#
con. execute ( """ INSERT INTO rur VALUES (NULL, '' ) """)
except sqlite3.DatabaseError as err:
printi"Ol!a:", err)
else:
print 1" m")
try:
with con:
#
con. execute 1"" "INSERT INTO rur VALUES INULL, '' ) """)
# 1 !
con.executei"""INSERT INTO rur VALUES 11, '')""")
except sqlite3.DatabaseError as err:
printi"Ol!a:", err)
else:
print 1" m")
con. close 1)
input 1)
, n n "" n
.

IntegrityError.

"n", "" , . .
n

ro1lback 1).

18

. W
, , . ,
, . .

Python

.
: URL-apeca ,
, L-, ,

18.1.

http. client

urllib. request.

URL-apeca

urllib.parse URL-apeco. ,

URL-apec,
. URL-apec r :
<>://<>:<>/<>;<>?<n>#<>

URL-apeca

FTP

-:

<>://<>:<>@<>

URL-apec urlparse ( 1:
urlparse(<URL-apec>[,

<>[,

<

>]])

ParseResult URL-apeca.

.
:

(scheme, netloc, path, params, query, fragmentl.

URL-apeca:

<scheme>://<netloc>/<path>;<params>?<query>#<fragment>.
, . .
.
URL-apeca

18.1.

~~~~;1-a:i"~~~~p tiRL~;;;t~~;;~~~~;~;~~;i;;;;<i'

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .!

. : :,,,,,,,;,;:::: : : : . :.:.: : ......... , ;:.=i ; ;.;,,,, ,,,,;,, ................... ; ............................................................................

>>> from urllib.parse import urlparse


>>> 11rl = urlparse ( "http: 1 /wwwadmin. ru: 80/test .php; st ?var=S#metka" 1
>>> url

18.

341

ParseResult(scheme= 1http 1, netloc= 1wwwadminoru:80 1, path= 1/testophp 1,


params= 1st 1, query= 1var=5 1, fragment= 1metka 1)
>>> tuple(url) #
( 1http 1, 1wwwadmin.ru:80 1, 1/testophp 1, 1St 1, 1Var=5 1, 1metka 1)

urlparse () ,

, URL-apeca.
. :

> urlparse ( "1 /wwwadmin. ru/test php")


ParseResult(scheme= 11, netloc= 1wwwadminoru 1, path= 1/test.php 1,
params= 11, query= 1 1, fragment= 1 1)
> t,~rlparse ("1 /wwwadmin ru/test php", "http")
ParseResult(scheme= 1http 1, netloc= 1wwwadminorU 1, path= 1/testophp 1,
params= 1 1, query= 1 1, fragment= 11)

ParseResul t, urlparse (), :

scheme -

. .

. :.

>>> url. scheme, .url [0]


( 1http'1, 1http 1)

netloc

1.

. :

>>> urlonetloc, url[l]


( 1wwwadminoru:80 1, 1wwwadminoru:80 1)

+
+

hostname -

. :

None;

port- . : None. :
>>> urlohostname, urloport
( 1wwwadmin.ru 1, 80)

path- . 2. .
:

>>> urlopath, url[2]


( 1/test.php 1, 1/testophp 1)

params- . 3.
. :

>>> urloparams,
(1st 1' 1st 1)

url[]

query- . 4.
. :

>>> urloquery, url[4]


( 1Var=5 1, 1Var=5 1)

fragment- . 5. .
:

>>> urlofragment, url[5]


( 1ffietka 1, 1metka 1)

342
n u

ur1parse 1)

True.

fragment.

fa1se,

/.

Python 3

>>> u = ur1parse("http://site.ru/add.php?v=S#metka")
>>> u.query, u.fragment
1' v=S ' , 'met ka ' )
>>> u = ur1parsel"http://site.ru/add.php?v=S#metka","",fa1se)
>>> u.query, u.fragment
1'v=S#metka', '')

+
+

username-

n. :

password-

n. :

None.

None;

>>> ftp = ur1parse("ftp://user:123456@mysite.ru")


>>> ftp.scheme, ftp.hostname, ftp.username, ftp.password
('ftp', 'mysite.ru', 'user', '123456')

getur1 1)

- URL-apec. :

> ur1. getur1 ()


'http://wwwadmin.ru:BO/test.php;st?var=S#metka'
n nu ( URL-apec ) n
u

ur1unparse 1<>) ( 18.2).

~~~~;~:2~-iri~~~~~4:~~~~it~4:;;;;;.~~~:,;-:::~-:;::--------;------

~ ~ ~

;;..... ............ :.; ... ... ....... ...... ::.........

>>> from ur11ib.parse import ur1unparse


>>> t = l'http', 'wwwadmin.ru:BO', '/test.php',
>>> ur1unparselt)
'http://wwwadmin.ru:BO/test.php?var=S#metka'
>>> 1 = ['http', 'wwwadmin.ru:BO', '/test.php',
>>> ur1unparse(1)
'http://wwwadmin.ru:BO/test.php?var=S#metka'

[,

<>[,

. . . . . . . . .!

:.~.............~...~.;.;, .. ;.~ . ::.. ,..:;;,.. ;;..~~; .,.,.. ,;.:.;........ ;...:....;;,,,;................. ;..~;.,,;;,;;~;,~.;;", ;,; ....... ;,;;;:.............; .............................. :....................................... ~

ur1parse ()

< >]

J).

'var=S',

'metka')

'var=S',

'metka']

ur1sp1i t 1<URL-apec>
Sp1itResult

URL-apeca. n :

lscheme, net1oc, path, query, fragment).

. n u

ur1sp1it () n

18.3.

'" .... ,.............................,....................... ,...................................................-........................................ ..,,.",, .. ,, .. ,.., .. ,,,."" ......


[ llr 1s:. URL-~j)eca ~ n~}() urlspiit ()
;

;;

........ ,,,.,.,,.,,,, .. ,, ... ,......... , ........ ,,,,,.,, ,., .......... ,, .. ,,., .. ,.

. . .
.
.....-........... ................................... ...................... ... :......................

................ ... .............. ...... :..................... ~ ..... ........ ;~;..............; .....,;,,,;,,.,,;, .... ,;.;,, ... ........... ............. ..,;:;
;

,.,,.,~,

;;

:;

>>> from ur11ib.parse import ur1sp1it


> ur1 = ur1sp1itl"http://wwwadmin.ru:80/test.php;st?var=S#metka")
>>> url
Sp1itResu1t(scheme='http', net1oc='wwwadmin.ru:80',
path='/test.php;st', query='var=S', fragment='metka')
>>> ur1(0], ur1(1], ur1(2], ur1(3], ur1(4]
l'http', 'wwwadmin.ru:BO', '/test.php;st', 'var=S', 'metka')

~ :

"'''"'''';;;

18.

343

>>> url.scheme, url.netloc, url.hostname, url.port


l'http', 'wwwadmin.ru:80', 'wwwadmin.ru', 80)
>>> url.path, url.query, url.fragment
1'/test.php;st', 'var=S', 'metka')
> ftp = urlsplitl"ftp://user:l23456@mysite.ru")
>>> ftp.scheme, ftp.hostname, ftp.username, ftp.password
l'ftp', 'mysite.ru', 'user', '123456' \
n ( URL-apec )

urlunspli t 1<>) (
~-:,~;;~~~;1:~~~~~~~~~~~~;~-~~~~--~1~;ii~<:

18.4 ).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .;

;.............................................. ;............................. ;.... ., .......... ~ ........~ ............................; ........~ .....=.;;;.,.;; .;.............. ;...~..... : ...... ;.......................... < : .............................................................,j

>>> from urllib.parse import urlunsplit


>>> t = l'http', 'wwwadmin.ru:80', '/test.php;st',
>>> urlunsplit (t)
'http://wwwadmin.ru:80/test.php;st?var=S#metka'

18.2.

'var=S',

'metka')


URL-apec .
, <n> .
n , n=. n

%nn. n, n str, "" Windows-

]251,

n :

str=~Dl~F2tFO~EE~EA~EO

n n=,
&. n

v 10:

str=%Dl%F2%FO~EE%EA%EO&v=l0

n n ,
.

n,

n n

:
str=%Dl%F2%F0%EE%EA~EO&v=l0&v=20

n n

urllib.parse:

parse ~qs 1) - n ,
n, n . :
parse~qs(<Cpoa

keep~ank~values=False] [,
[, encoding='utf-8'] [, errors='replace'])

n>[,

strict~parsing=False]

keep ~ank ~values

True,

n,

n, .
n n . n strict~parsing

344

/.

Python 3

True, ValueError.
. encoding .
errors- . :

>>> from urllib.parse import parse_qs


>>> s ~ "str~%D1%F2%F0%EE%EA"&E0&v~10&v~20&t~"
>>> parse qs(s, encoding~"cp1251")
{'str': [''], 'v': ['10', '20']}
>>> parse_qs(s, keep_ank_va1ues~True, encoding~"cp1251")
{'t': ["], 'str': [''], 'v': ['10', '20'])

parse qsl 11 - parse_ qs 11, ,


. ,

.
, . :
parse_qsl(<Cpoa

>[,

strict_parsing~False]

[,

keep_ank_values~Fa1se]

encoding~'utf-8']

[,

[,

errors~'rep1ace'

Jl

>>> from llrl1ib.parse import parse_qs1


>>> s ~ "str~~D1'kF2%FO'oEE%EA%EO&v~10&v~20&t~"
>>> parse qsl(s, encoding~"cpl251")
[('str', ''), ('v', '10'), ('v', '20')]
>>> parse qs1(s, keep_ank_values~rue, encoding~"cp1251"1
[('str', ''), ('v', '10'), ('v', '20'), ('t', ")]
.

urlencode ( 1 url1ib.parse. :

urlencode(<Oe>[,

doseq~False]

[,

safe~'

'] [,

encoding~None]

[, errors=None] 1
,
.
, .

quote plus () urllib. parse.

', ,

18.5.

!. .~.~~~~.. ~.~~.~. . ~~~...~~~. ~:~~.<.>.. . . . . . . . . . . . . . . :. . . . . . . . . . . . . . . . . . . . . . . . ;. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


>>> from ur1lib.parse import urlencode
>>> params ~ {"str": " 2", "var": 20}
#
>>> urlencode(params, encoding="cpl251")
'var=20&str~'l %F2;FO%EE%EA%E0+2'
>>> params ~ [ ("str", " 2"), ("var", 20) ] #
>>> urlencode(params, encodig~"cp1251")

'str~%D1%F2%FO%EE%EA%E0+2&var=20'

doseq ur1encode 1) True.


.

18.

345

doseq ~ False.

18.6.

18.6).

~~~~
............................... ; ................................... ..

> params = [ l"var", [10, 20]) ]


> urlencodelparams, doseq=False, encoding="cpl251")
'var=%5B10~2C+20~5D'

> urlencodelparams, doseq=True, encoding="cp1251")


'var=10&var=20'
:

>>> params = { "var": [ 10, 20] )


>>> urlencodelparams, doseq=True, encoding="cp1251")
'var=10&var=20'

u

113

urllib.parse:

quote 1) ~ u nn. ,

(_j,

(.)

(-) .

%20. u:
quotei<Cpoa>[,

safe='/'] [, encoding=None] [, errors=None])

safe , .
1. encoding
, errors ~ . :

>>> from url1ib.parse import quote


> quotei"Cpoa", encoding="cp1251")
'' F2% FO'bEE'i>EA,EO'
>>> quotei"Cpoa", encoding="utf-8")

Windows-1251
UTF-8

'%DO%Al%DH;82?;01%80%DO%BE'O'iiBMDO%BO'

>>> quotel"/-nik/"), quotel"/-nik/", safe='"')


1' /');7Enik/', '%2F%7Enik%2F')
>>> quotel"/-nik/", safe="/-")
'/-nik/'

quote_p1us 1) ~ u quote 1), +,


%20. , 1
:;2r. u:
quote _1 us 1<> [, safe=' ' ] [, encoding=None] [,
:

>>> from urllib.parse import quote, quote_plus


>>> quotei"Cpoa 2", encoding="cp1251")
'%01 ~.F2%F%''%202'
>>> quote_plusi"Cpoa 2", encoding="cp1251")
'%D1%F2%F0%EE%EA~E0+2'

> quote_plusl"/-nik/")

rrors=None

l)

346

1.

Python 3

'%2F%7Enik%2F'
>>> quote_plus("/-nik/", safe="/-")
'/-nik/'

quote_ from_ bytes () -

quote (),

, . :
qut_frm_ts(<

>[,

safe='/'J)

>>> from urllib.parse import quote_from_bytes


>>> quote_from_bytes(bytes("Cpoa 2", encoding="cpl251"))
'%Dl%F2%FO%EE%EA%E0%202'

unquote () - %nn . +
. :

unquote (<> [, encoding=' utf-8' ] [, errors=' replace' ] ).


:

>>> from urllib.parse import unquote


>>> unquote("%Dl%F2%FO%EE%EA%EO", encoding="cpl251")
''

> s = "%DO%Al%Dl%82%Dl%80%DO%BE%D0%A%DO%B0"
>>> unquote(s, encoding="utf-8")
''

>>> unquote('%Dl%F2%FO%EE%EA%E0+2', encoding="cpl251")


'+2'

unquote_plus () _:_ unquote (), +


. :
unquote_plus(<Cpoa>[,

encoding='utf-8'] [, errors='replace'])

>>> from urllib.parse import unquote_plus


>>> unquote_plus("%Dl%F2%FO%EE%EA%E0+2", encoding="cpliSl")
' 2'
> unquote_plus("%Dl%F2%FO%EE%EA%E0%202", encoding="cpl251")
' 2'

unquote_ to_ bytes () -

unquote (),

I(!
. :
unquote_to_bytes(<Cpoa n

>)

>>> from urllib.parse import unquote_to_bytes


> unquote_to_bytes("%Dl%F2%FO%EE%EA%E0%202")
b'\xdl\xf2\xf0\xee\xea\xe0 2'
> unquote_to_bytes(b"%Dl%F2%FO%EE%EA%E0%202")
b'\xdl\xf2\xf0\xee\xea\xe0 2'
> unquote_to_bytes("%DO%Al%Dl%82%Dl%80%DO%BE%DO%BA%DO%BO")
b'\xd0\xal\xdl\x82\xdl\x80\xd0\xe\xd0\xba\xd0\xb0'

>>> str ( , "utf-8")


''

18.

347

18.3.


L- , .

URL-apece

, , n

href

<base>.

URL-apec n urljo 1J

urllib.parse.

urlJoini<ao

[,

URL-apec>,

<

<

URL-apec>

>])

n n (

t 8.7).

[' 18.7. n

f,.,;,,,,,,,..,,,,,,,,.,,,,,,.,,,,.,,.,,.,.,,,,,,,,,,,,,,,,,.,.,,.,,,,.,;,.,;,,.,,..,,,,,,,:,,,;,),.,:,.,,,,,,,,.,,.,;,;;,:;,;,:,.,,,,,:,,;,,,,,,,,,.,,,,;,.,,.;,,.,,,.,,,,.,,,,.,.,,,;,,,,,,,,,"'';,;,;;,.,,,,,,,;,;,,,,,,,,,.,,.,,,,,.,,,,,,,.,,,,,_,,,,.,,,,,,,;;,,,,,,,,.,,,,,.J

>>> from urllib.parse import urljoin


> urlJoin 1'http: 1 /wwwaclmin. ru/fl/f2/test. html',
'http://wwwadmin.ru/fl/f2/file.html'
> urlj oin 1'http: 1 /wwwadmin. ru/fl/ f2/test. html',
'http://wwwadmin.ru/fl/f2/f3/file.html'
> urlJoin 1'http: 1 /wwwadmin. ru/fl 1 f2/test. html',
'http://wwwadmin.ru/file.html'
> urlj oin 1'http: 1 /wwwadmin. ru/fl/ f2/test. html',
'http://wwwadmin.ru/fl/f2/file.html'
> urlj oin 1'http: 1 /wwwadmin. ru/fl/f2/test. html',
'http://wwwadmin.ru/fl/file.html'
> urljoin 1'http: 1 /wwwadmin. ru/fl/f2/test. html',
'http://wwwadmin.ru/file.html'
> urlJoin ( 'http: 1 /wwwadmin. ru/fl/f2/test. html',
'http://wwwadmin.ru/ .. /file.html'

'file. html' 1
'f/file.

html')

'1 file. html' 1

' . /file. html')


' .. 1 file. html' )
' .. 1 .. /file. html')
' .. 1 .. 1 .. /file. html')

n n , .

, .

18.4.

L-

L- n. n, ""
(<) ""

. n n

(> ),

L-. n, "" n & 1 t;,


""

&gt;. n
xml. sax. saxutils:

si<>[,

L-

<>])- <,> & L

. n <> n n
L-
. :

>>> from xml.sax.saxutils import escape


>>> s = ''''''&<>''

111111

348
>>> escape(s)
'&amp;&lt;&gt;" '
>>> escape (s, {

"&quot;

11

11

"

"&nsp;"

/.

Python 3

} )

'&amp;&lt;&gt;&quot;&nsp;'

quoteattr (<> [,

<>]) - escape (), n

n.
, n.
, n, L-,
. n ,
. :

>>> from xml.sax.saxutils import quoteattr


>>> print (quoteattr("""&<>" """))
'&amp;&lt;&gt;" '
>>> print(quoteattr("""&<>"'"""))
"&amp;&lt;&gt;&quot; '"
"&quot;" ) ) )
>>> print (quoteattr ("""&<>" """, {
"&amp; &lt; &gt; &quot; "

unescape (<> [,

<>]) -

L- &amp;, &1 t;

&gt;

. n <> n
n L-
. :

>>> from xml.sax.saxutils import unescape


>>> s = '&amp;&lt;&gt;&quot;&nsp;'
>>> unescape(s)
'&<>&quot;&nsp;'

"&quot;":

>>> unescape(s,
'&<>"

": " " } )

<, >

& L- n

escape (<> [, <> J ) cgi. n

rue,

"&nsp;

Python 3.2

escape

L- (

18.8).

n . n

(<>

[, quote=True])

html.

>>> import cgi, html


>>> cgi.escape(''''''&<>''' ''''''), html.escape(''''''&<>''' '''''', False)

('&amp;&lt;&gt;"\' ', '&amp;&lt;&gt;"\' ')


>>> cgi.escape("""&<>''' """, True), html.escape{"""&<>"' """, True)
("&amp; &lt; &gt;&quot;' ", '&amp; &lt; &gt; &quot; &#27; ')

18.5.

http. client n n

HTTPS.

no

n n GET, :s HEAD.

, n n , n

HTTPConnecoon.

18.

349

:
HTTPConnectio (<>

[,

[, strict [, timeout [, source address]]]])

<>

n n. n
n. n , n n

80.

n . :

>>> from http.client import HTTPConnection


>>> con = HTTPConnection("test1.ru")

> con2

HTTPConnection("test1.ru", 80)

>>> con3 = KTTPConnection("test1.ru:80")


n n n n

request ( 1

request(<Meo>,

<>[,

body=None] [,

hdrs=<>])

n n

(GET, POST HEAD). n


GET, n

n . n

n . n .
, n

POST. n

. n -, n
. .

n n
( ) n
.

read ( 1

getresponse (). ~
read ( [< >]). n

, n -

n . ,

. n n, n n

. read ( 1 n , .
n

close ( 1.

n n n

GET

18.9).

: ... " ' ...... ' .. " . ' . ' ' " ................. .. ' ' .. ' .... ' . !: ...... '.' .' '.. . . : . . . . . . ........ .................... ' .................... ' . ' ' ' .........
~

~ ~

~ 18.9. GET

t:......... ,............ ............ :.......... ,; ........ :............. " ~ ..:;. :....~ ............ ;i,.;,;;,,;,,!... :.... ;,;,, ~:..... ;;,, .. ................................. .

>>>
>>>
>>>
>>>

>>>
>>>
>>>
>>>

from http.client import HTTPConnection


from urllib.parse import urlencode
data = urlencode ( { "color": "", "var": 15}, encoding="cpl251")
headers = { "User-Agent": "MySpider/1.0",
"Accept": "text/html, text/plain, application/xml",
"Accept- Language": "ru, ru-RU",
"Accept-Charset": "windows-1251",
"Referer": "/index.php" }
con = HTTPConnection ( "testl. ru")
con.request("GET", "/testrobots.php?%s"% data, headers=headers)
result = con.getresponse() #
print(result.read() .decode("cp1251")) #

>>> con. close ()

n n

"POST",

POST.

n n

request ()

n n. -

350
npoca

POST n

/.

Python 3

Content-Length. n

\8.1 .

.. ..
.
... :.:..:::'~~-,:~-"~,~::,~~:::~:~.:.~~.'.':~::"-~ .. ~:-~ .. ..:"~ ............ ~ .......... >
[(ttr 18.1. n1:.1i:t:QS1'
. . ... . . .. .
~-~=.:\ ... ~;,,:,.,,,,;:...... :.: .. ;;;,:: ...=.=::.~.. :.;:.;;,.: ~:.:.;~.;: ..... :;::.: ::~-;(:.~~;;: . :~: :.-:;:~;,;~ :;,;;, .. :=:.:.~ ...... :::.: . ::.'...... ::: ...... :: .....
~~.:~:-~::.:~~::~~7'.'~~..~:~:~~,~~-~:~~ ~:.::,~~-~~,:.~:~.~:-~-:::.~:~.::~-:~~-~;,::::;.-~:~::~ .:,~:::~;:-::

=. . . . . . . . . . . . : ....: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

...............

~ ...................... :

, , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .: ;

>>> from http.client import HTTPConnection


>>> from urllib.parse import urlencode
>>> data = urlencode ( { "color": "", "var": 15), encoding="cpl251")
>>> headers = { "User-Agent": "MySpider/1. ",
"Accept": "text/html, text/plain, application/xm1",
"Accept-Language": "ru, ru-RU",
"Accept-Charset": "windows-1251",
"Content-Type": "application/x-www-form-urlencoded",
"Referer": "/index.php" )
>>>
>>>
>>>
>>>

con = HTTPConnection("test1.ru")
con.request("POST", "/testrobots.php", data, headers=headers)
resu1t = con.getresponse() #
print (result.read() .decode("cp1251"))

>>> con. close ()


Content-Type.
application/x-www-fon-urlencoded, , n .

n. n, n n 1

$_s.

, $ _ros n

.
n :

getheader (<> [, < >]) -

. ,

None

n. :

>>> resu1t .gethead~r ( "Content-Type")


'text/p1ain; charset=windows-1251'
>>> print (result.getheader("Content-Types"))
None
>>> result.getheader("Content-Types", 10)
10

getheaders () -

n .

(<>,

<>). n

>>> result.getheaders()
[('Date', 'Mon, 02 2011 11:09:37 G'), ('Server', 'Apache/2.2.4
(Win32) mod_ssl/2.2.4 OpenSSL/0.9.8d /5.2.4'), ( 'X-Powered-By',
'/5.2.4'),
('Content-Length', '422'), ('Content-Type',
'text/plain; charset=windows-1251')]

18.

351

dict () :

>>> dict(resu1t.getheaders())
{'Date': 'Mon, 02 2011 11:09:37 G', 'Content-Length': '422',
'X-Powered-By': '/5.2.4', 'Content-Type': 'text/p1ain;
charset=windows-1251', 'Server': 'Apache/2.2.4 (Win32)
mod_ss1/2.2.4 OpenSSL/0.9.8d /5.2.4')

status- . 200 299

304,

, .

301 302 . 401


403- , 404- ,

500

. :

>>> resu1t.status
200

reason- . :
>>> resu1t.reason

200

302

''

>>> resu1t.reason
'Moved Temporari1y'

version- . 1 /1.0 11
/1.1. :

>>> resu1t.version
11

/1.1

msg- http.client .TPMessage. f


. print (),
:

>>> print(resu1t.msg)
Date: Mon, 02 2011 11:09:37 G
Server: Apache/2.2.4 (Win32) mod ss1/2.2.4 OpenSSL/0.9.Bd
X-Powered-By: /5.2.4
Content-Length: 422
Content-Type: text/p1ain; charset=windows-1251

as_string ( [unixfrom=Fa1se] [,

/5.2.4

http.client.HTTPMessage:

maxheader1en=O]) -

. :

>>> resu1t.msg.as_string()
'Date: Mon, 02 2011 11:09:37 G\nServer: Apache/2.2.4 (Win32)
mod_ss1/2.2.4 OpenSSL/0.9.Bd PHP/5.2.4\nX-Powered-By:
PHP/5.2.4\nContent-Length: 422\nContent-Type: text/p1ain;
charset=windows-1251\n\n'

items () -

. :

>>> resu1t.msg.items()
[('Date', 'Mon, 02 2011 11:09:37 G'), ('Server', 'Apache/2.2.4
(Win32) mod_ss1/2.2.4 OpenSSL/0.9.Bd /5.2.4'), ('X-Powered-By',

352
1
1

2. 4 1 ) , ( 1 Content-Length 1 , 1 422 1 ) ,
text/p1ain; charset=windows-1251 1 ) ]
/5.

keys ()

va1ues ()

Python 3

Content-Type 1 ,

Content-Length 1 ,

Content-Type 1 ]

- . :

>>> resu1t.msg.va1ues()
1
[
Mon, 02 2011 01:09:37
OpenSSL/0.9.8d /5.2.4 ,
charset=windows-1251 1 ]
1

- . :

>>> resu1t.msg.keys()
1
[
Date 1 , 1 Server 1 , 1 X-Powered-By 1 ,

/.

G
1

Apache/2.2.4 (Win32) mod_ss1/2.2.4


1
, 1 422 1 ,
text/p1ain;

/5.2.4

get (<:> [, failobj=None]) -


. , None
.. :

>>> resu1t.msg.get("X-Powered-By")
1

/5.2.4

>>> print (result .msg .get ( "X-Powered-By2"))


None
>>> resu1t.msg.get("X-Powered-By2", fai1obj=10)
10

get all (<:>[, failobj=None])-

~. , None
. RJiep:

>>> resu1t .msg .get_all ( "X-Powered-By")


/5. 2. 4
[

get _ content _ type () -

I-

Content-Type:

>>> resu1t.msg.get_content_type()
1
text/p1ain 1

get_content_maintype ()

- I-:

>>> resu1t.msg.get_content_maintype()
1
text 1

get_content_sutype

() - I-:

>>> resu1t.msg.get_content_sutype()
1
p1ain 1

get_content_charset ( [failobj=None])-
Content-Type. , None
fai1obj. :
>>> result .msg .get_content_charset ( ).
1
Windows-1251 1

HEAD

18.11 ).

18.

353

>>> from http.client import HTTPConnection

> headers = { "User-Agent": "MySpider 11. ",


"Accept": "text/html, text/plain, application/xml",
"Accept-Language": "ru, ru-RU",
"Accept-Charset": "windows-1251",
"Referer": "/index.php" }
>>> con = HTTPConnection("test1.ru")
> con.request("HEAD", "/testrobots.php", headers=headers)
>>> result = con.getresponse() #
>>> prlnt(result.msg)
Date: Mon, 02 2011 12:33:46 GMT
Server: Apache/2.2.4 (Win32) mod_ssl/2.2.4 OpenSSL/0.9.8d /5.2.4
X-Powered-By: /5.2.4
Content-Type: text/plain; charset=windows-1251

> resul t. read () #

''

> con.close ()
- :

+
+
+
+
+
+
+
+
+
+
+
+
+
.+

GET- GET;
s- s;

Host -

Accept-

I-, W-;

Accept-Language

~ ;

Accept-Charset-

Accept-EncodingContent-Type-

Content-Legth- s;

Cookie-

cookies;

Last-Modified- ;
Location-

URL-apec;

Pragma- ,
cacrle-Control -

/1.0:

/1.1;

Referer-

Server- ;

user-Agent -

URL-apec, ;

W-.



12

1349

RFC 2616,
http://www.w3.org/Protocols/rfc2616/rfc2616-secl4.htm1.

"' 1

/.

354
,

Firebug Firefox.

W-

18.6.

Python 3

ieHTTPHeaders

W-

lnternet Explorer.

urllib.request

urllib. request
.

Location, ,

urlopen(<URL-apec >[,

cookies

urlopen (). :

<>][,

<->]

[, cafile=None] [, capath=None])
URL-apec ,

Request. GET,

, s . POST

Content-Type application/x-www-form-urlencoded.

: ,
urlopen (), :

read ( [< > J) -

. ,

,
. , . :

>>> from urllib.request import urlopen


>>> res = urlopen ( "http: 1 /testl. ru/testrobots .php")
>>> print (res. read (34) .decode ( "cpl251"))
: Python-urllib/3.2
> print(res.read() .decode("cpl251"))

>>> res.read()
''

readline ( [< >] ) -

.
, ,

(\n),

, ,

, .

, . :

>>> res = urlopen ( "http: 1 /testl. ru/testroots .php")


> print (res. readline () .decode ("cpl251"))
:

Python-urlli/3.2

readlines ( [< > J) -

. i

, .
, .
.

18.

355

> res

~ urlopen("http://testl.ru/testrobots.php")
>>> res.readlines()
[b'\xcd\xe0\xe7\xe2\xe0\xed\xe8\xe5 \xf0\xee\xe1\xee\xf2\xe0:

Python-urlli/3.2\n']

>>> res.readlines()

>>> res.readl1nes()
[]

_next_l)- n .
_ next _ ()
n n n for. for
_ next _ (). :

Stopiteration.

>>> res ~ urlopen("http://testl.ru/testrobots.php")


>>> for line in res: print(line)

+
+

close () - ;
geturl 1) URL-apec n . nn
1 , URL-apec n
n URL-apeco, n;

info () -

, n n

n http.client (. msg ). :

>>> res ~ urlopen("http://test1.ru/testrobots.php")


>>> info ~ res.info()
> info.items ()
[I'Date', 'Mon, 02 201112:01:44 G'), ('Server', 'Apache/2.2.4
(Win32) mod_ssl/2.2.4 OpenSSL/0.9.8d /5.2.4'), ( 'X-Powered-By',
'/5.2.4'),
('Content-Length', '288'), ('Connection', 'close'),
( 'Content-Type', 'text/plain; charset~indows-1251') ]
>>> info.get ("Content-Type")
'text/p1ain; charset~windows-1251'
>>> info.get_content_type(), info.get content_charset()
( 'text/plain', 'windows-1251')
>>> info.get content_maintype(), info.get_content sutype()
( 'text', 'p1ain')

+
+

code- ;
msg- . :
>>> res.code, res.msg
(200, '')

n n n GET s (

>>> from url1ib.request import urlopen


>>> from ur11ib.parse import ur1encode
>>> data ~ ur1encode ( {"co1or": "", "var": 15},

18.12).

encoding~"cp1251")

356
>>>
>>>
>>>
>

Python 3

# ~ GET
ur1 = "http://test1.ru/testrobots.php?" + data
res = ur1ope(ur1)
print ( res. read ( 34) . decode ( "1251") )
Python 7 ur11i/3.2

>>>
>>>
>>>
>
>

/.

res. c1ose ()
# ~ POST
ur1 = " http://test1.ru/testrobots.php"
res = ur1open(ur1, data.encode("cp1251"))
print 1res. read () .decode ( "1251"))

>>> res.c1ose()

"Python-urlli<Bepc

Python>".
, Request ur1open ()
URL-apeca. Request :
Request(<URL 7 apec>[,

[,

data=None] [, headers={}] [, origin_req_host=None]


unverifiae=Fa1se])

URL-apec.
,

POST

GET,

POST Content-Type
app1ication/x-www-form-ur1encoded.
. cookies.
.

GET s ( 18.1 3).

i .r 18;13. n
>>> from ur11ib.request import ur1open, Request
>>> from ur11ib.parse import ur1encode
>>> headers = { "User-Agent": "MySpider/1.0",
"Accept": "text/htm1, text/p1ain, app1ication/xm1",
"Accept-Language": "ru, ru-RU",
"Accept-Charset": "windows-1251",
"Referer": "/index.php" }
>>> data = ur1encode 1{ "co1or": "", "var": 15}, encoding="cp1251")
>>> # ~ GET
>>> ur1 = "http://test1.ru/testrobots.php?" t data
>>> request = Request(ur1, headers=headers)
>>> res = ur1open(request)
>>> printlres.read(29) .decode("cp1251"))
: MySpider/1.0
>>> res. c1ose ()
>>> # ~ POST
>>> ur1 = "http://test1.ru/testrobots.php"
>>> request = Request(ur1, data.encode("cp1251"), headers=headers)
>>> res = ur1open(request)

>

18.

357

prt(res.read()
~

.decode("cpl251") 1

> res. close ( 1


,

18.7.

"MySpider/1.0".

. n
, .

Content-Type

Content-Type: text/html; charset=utf-8


L- n

<meta>,

content

HEAD:

<meta http-equiv="Content-Type"
content="text/html; charset=windows-1251">
,

<meta>, .
chardet.

http://chardet.feedparser.org/download/

python3-chardet-2.0.1.tgz,
WinRAR.

, ,

n (

cd

C:\book),

C:\book\python-chardet-2.0.1

, :
C:\Python32\python.ee

setup.py install

IDLE

Python Shell

>>> import chardet


>>> chardet. version
'2. .1'

detect (< >).


encoding
. confidence-
.

1).

18.14.

'" ... ". "''' .. '""""."'" . ' .. '." .. '"."".' ... ' "' . "." ..... " . " '" ' ... '' . '' . '"" ".'." ..... '' .. '."""" '' ''"" . ~ '" .. '" ...... :... '' ........ -~ ... " "!" "' ....... '"! . ............................ ,....... '' .. '''." ............. ~ .............. '.

f 18.14.

;'""""""'""'"~''"'"''""'~"""""""'''""'''v;,,.,,,,.,,,,~,,,:: .. ,,.,,,,,,,;;;.,,,..,,,,,,,.;,,,...,,,.,,,,..,,,,.,;,.;.:;,.~;;,,v,','i,;,,,~,,,,.~.,;,.,,:v., ..~,:;,,.,, ..V,.,.;,,:;.,:,;,;;,~.~;;;,~'"""'""'"""':,,,;,,,.,~.,;,;.,,,,..;,,,.voo""'"""'""'j

>>> import chardet


>>> chardet.detect(bytes("Cpoa", "1251"11
{ 'confidence': 0.99, 'encoding': 'windows-1251'}
>>> chardet.detect(bytes("Cpoa", "koi8-r") 1
{ 'confidence': 0.99, 'encoding': 'KOI8-R'}
>>> chardet.detect(bytes("Cpoa", "utf-8"1 1
{'confidence': 0.99, 'encoding': 'utf-8'}

358

/.

Python 3

, n

detect ( 1

Uni versalDetector.
feed ( 1. n


n n,

done

rue.

n .

close ( 1.

n n

result.

n n n

reset ().

UniversalDetector

18.15.

# -*- coding: utf-8 -*from chardet.universaldetector impqrt UniversalDetector


ud = UniversalDetector()
#
for line in open ("file. txt", "rb"):
ud.feed(line)
#
if ud.done: break
# , done
ud.close ( 1
#
# rn
print(ud.result)
input ()
n , n n

True

Windows-1251

n. n ,
n .

5 .

UTF-8

6500

UniversalDetector

- .

11

19.

20.

21.

22.

23.

24.

25.

26.

27.

28.

PyQt

SDI-

DI-

19

PyQt,

PyQt

Python

, n

n n .

, n

, n.
. n

. (

750

no

.) .

, , -,

, . .

.
.

19.1.

PyQt

PyQt

Python.
PyQt .

PyQt-Py3.2-x86-gpl-4.8.3-l.exe

1.

http://www.riverbankcomputing.eo.uk/software/pyqt/download

2.

(.

3.

(.

4.

(.

19.1)

19.2)
19.3)

Next.

19.4) ,
Python (C:\Python32\). lnstall

(.

6.

1 Agree.

, .

5.

Next.

PyQt.

, .

Finish

19.5.

Lib\site-packages\PyQt4\,

C:\Python32\

C:\Python32\Lib\site-packages\PyQt4\in. in - Designer,

Linguist Assistant, (, QtCore4.dll,


QtGui4.dll), ,

11.

362

his wiz4!"d 1 QUde you tt-.ou tho instol<ltioo of PyQt

GPI. V'\.6.3 for Python v.z (66).

This of PyQt lnWdes ..Set Qt v1. 7, 1 Open Soorce


Edition needed PyQt. lt olso lnWdes ySQl, ,
Post<,oSQl and ~ drlvers anq tho reqlirod OpenSSl
DUs.

Arrf codo you wrte must releosod under kense thot ls


wth tho GP\..

CkkNext to COitlnue.

(::t >
.

19.1. PyQt.

J 1 cancd

Licene Agreemonl
Ple- revlew tho lcense terms efore lnstoik>Q PyQt.

GNU GENERAL PUI.IC UCENSE


PyQt ls Copyrlt

() 2011 RJvet!Iik Compo.rt\Q

Llmltod

VOJ use, <istrble ond PyQt under the terms of


GNJ Gener~ 1'\ Ucense verslon 2 or verslon , whlch 41"
dlsplayed eloW.

GNJ GENERAL PUUC UCENSE

PyQt.

19.2. ~ PyQI. 2

, in

MySQL.

libmySQL.dll,

n C:\Python32\Lib\site-packages\PyQt4\in

libmySQL.dll

n . W-n

MySQL 5.2,
libmySQL.dll. . ,

n in , n, .
n n ,

PyQt Qt ( 19.1 ).

19.

363

PyQt

Chooae C4mponenta
Choose ..toi:h fe<'lt..-es d PyQt you want to instal.

Sel~~th81Yj)8 d ~;

01' S(!led: tj!e~

Extensm~

c~syou-hto

QScWJIIa

~:

E]Qtr~.rotime

EJ Doveloper tools

EJ Qt developer tools

EJ SIP ~eloper tools


EJ Ooam!nt.ion

e]Ex1111"4)1es

EJ st.vt ertJ shorta.ts

i"''''''' ~''

000

00

00

~ "'"'"''''\00f"'

.. '

PyQt. War 3

19.3.

19.4. PyQt. War 4

"'"f'''._''I'~"''''~I."'"''''I""'''"'"'''''''"~'~''..'"'"!' ... Ooo.IOOfo')\Ot"'"''tO"''"''" ' ""'~"'''''''''.,"I''..-><'''''.,

~ 64r 19.1,ppspJ:Wt npaI}I>tiQ~ ~~" Py()t

'''' "t:''''''''l'''''..'.0"'~'0~oo

V"'""~'"IH'"~'' ''"' ' ""'''''""'"''''"'''1

oo oo>o..O,oi,,,,.,...,,,_, ,,_.,J.,,,,.,.,,, ,,o4,oo... .n,..,_,,looo"t'..' ' ...''''Doo-.~:.W1o-....,,,,.,,_,_.,...,},,Oio"""'-"''*"'-'-f+f<>~......w...,,...W,,..~, ..,.,,.,..,,.,_.,,.,..,,,....'>'_oO.ooo>.....-o-~o'''"'" - N.;.,.,,... ,,-~....,.;\-ioo...,.;

> from PyQt4 ix>rt QtCore


>>> QtCore.PYQ_VERSION_STR
'4 .8.3'

>

QtCor~.Q_VERSION_STR

'4. 7 .1'

364

11.

Completing the PyQt Setup Wizard

dick Fnsll to close this wi:Nd.

Get the latest news ol PyQt here

19.2.

19.5.

PyQI. 5

,
" , !".

19.2).

...~,., ...................\.'''''''''''''''''''""'''''''''"'''"''""'''''''''''"'''''''''\'!' .. ,, .. ,, ....... ~, ..,,............. ... ,...., .........................~"''"'"'' '"'"''''''''' ''''''''"'''"''"'................... , ................ ,, .............

:~

f...........
19.2. n PyQt
....................................,, _.;, ,.;..,,.......................... ........
;

......,. ...;......:...............................~ ~ ; ... ,.... ,.~.........~.,...............................,............................ ; ..........................;

# -*- coding : utf-8 -*from PyQt4 import QtCore, QtGui


import sys
= QtGui.QApplication{sys.argv)
window = QtGui. QWidget{)
window.setWindowitle{"epa n

wi ndow.resize{OO,

lael = QtGui .QLael ("<ntr> ,


btnQuit = QtGui .QPushButton( "&aprr
v

PyQt " )

70)
!

</c.enter>")

")

= QtGui.QVoxLayout()

vbox.addWidget{label)
vbox.addWidget{btnQuit)
window .setLayout(vbox)
QtCore .QObject .connect {btnQuit , QtCore.SIGNAL {"clicked () "),
QtGui .qApp, QtCor e.SLOT{"quit{) " ))
window . show ()
sys . exit(app.exec_ ())
-

IDLE.
IDLE PyQt, n -

19. PyQt

365

n . . ,
n n

{DLE ( <F5>) n n

. n
n .

IDLE n n PyQt n
Eclipse PyDev. n n

n , . ,
n , 1

. n

Eclipse .
Eclipse

n n . .

, n n .

.
, n n n .

(
). ,

pyw.

19.2 . 19.6.

...

'"rlep nporp.'III-~'

'Q{Q)fi

~t!OT,1'1!1PI

19.3.

)
1

19.6. 19.2

, ~ '
.

19.2 .
UTF-8

Python 3 , . .
QtCore QtGui. QtCore

PyQt. QtGui , n ,
n , , .
sys, ,
{argv), ti exit ( J, .

= QtGui. QApplicat i on(sys.argv)

QApplication.
n , . n,
, n .
, n ,
n .

n q

QtGui.

11.

n, n n, n ,

print(QtGui.qApp.argv())

window

QtGui.QWidget()

QWidget.

, n . n,
, .

window.setWindowitle("epa n

PyQt")

, .
window.resize(OO,

70)

. n n

resize ()

, n- . ,
, , . .

n n, .

label =

QtGui.QLabel("<center>pe,

p!</center>"}

n. n n

QLabel. , L-.
n n <center> n n.
n L- SS-

PyQt.

11, n

. .

btnQui t

QtGui. QPushButton ( "&;3~>:rr

")

n. , n, n

"3"''.

QPushButton.

& n

n.

<Ait>

, n &, n

vbox

= QtGui.QVoxLayout()

. n, ,
n n n .
n n n n .

n n.

vbox.addWidget(label)
vbox.addWidget(btnQuit)
n

addWidget () n !( n n

. n n, n

19.

PyQt

367

n. n , n
.

window.setLayout(vbox)
n

setLayout (). ,

n .

QtCore.QObject. connect (btnQuit, QtCore .SIGNAL ( "clicked () "),


QtGui.qApp, QtCore.SLOT("quit()"))

clicked (), n n.
connect () ,

n n

, n- . n
, n , n- ,
n . n .
n n, n
n

qApp.
quit (),

window. show ()
n, . , ,

sys.exit(app.exec_())
n . , n n

_(), n n .
n _ () n

exit (), n

, n n .

19.4.

600

PyQt

n - (-)

. ,

n n . , n ,
n n n n.

QWidget:

>>> from PyQt4 import QtGui


>>> QtGu~.QW~dget. bases
(<class 'PyQt4.QtCore.QObject'>, <class 'PyQt4.QtGui.QPaintDevice'>)
, QWidget - QObject QPaintDevice.
QObject , PyQt.
QWidget n.
, QWidget .
n , . . n

,
.

368

11.


. .
- (

19.2

19.3).

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyWindow(QtGui.QWidget):
def
init (self, parent=None):
QtGui.QWidget. lnit (self, parent)
self.label = QtGui.QLabel("pe, ")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.btnQuit = QtGui.QPushButton("&aprr ")
self.vbox = QtGui.QVBoxLayout()
self.vbox.addWidget(self.label)
self.vbox.addWidget(self.btnQuit)
self.setLayout(self.vbox)
self. connect (self. btnQui t, QtCore. SIGNAL ( "clicked () ") ,
QtGui.qApp.quit)
1

if

n
main
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
#

window.setWindowitle("OO-c

")

window.resize(300, 70)
window. show ()
#
sys.exit(app.exec_()) #

rr

QtCore

QtGui.

MyWindow,

QWidget:

class MyWindow(QtGui.QWidget):

QWidget ,
QWidget, QFrame ( ) QDialog (
). QDialog (

no

) - n

. ,

QMainWindow,

, .

QMainWindow

def

init

(self, parent=None):

. n n

(self) (parent).

n n

19.

369

PyQt

(None). _init_ ()

n n:

QtGui.QWidget.

init

(self, parent)

n, n

. n . .
. n n n
. n , n,
n. , n
n.

n n:
self.connect(self.btnQuit, QtCore.SIGNAL("clicked()"),
QtGui.qApp.quit)
n n (

19.2),

connect ()

QObject, n . , . .
QWidget, n QObject
connect (). n, n
connect (). n n , ,
- . n

, n n . , . .

Python

, n ,
.

19.2)

. n n
n

setAlignment ().

AlignCenter:

self.label.setAlignment(QtCore.Qt.AlignCenter)
n n

if

MyWindow n :

maln

n , n.

_n_

"_main_" n

n. n, .

n n n
n n n n .
n, . ? n - n
n n . , n
n

MyWindow

n. n

19.3

n (n,

MyWindow.py,
test.pyw)

19.4.

t~;~-~~-1:4::~~~~~~-~~ri~~~~~~~~:i&~~~~~~~;~::.

;:, ......... 1 1.. 1'.' . 1. " . '. ,,; . 1' . ,;, :; " ..... : ;: :'' :. ,;, : ;,.: .... ;"' '" ,', 1~: ,;,:;;: ii ~ ;; ;;,',;;,;:,~

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import MyWindow

i:,; .:: ;.:.: .i 1':.; ;:... 1::':' ;;:;;," :..... ::; .~'::' ' ........... :. ... ''

370

class MyDialog(QtGui.QDialog) :
def
init (sel f, parent=None):
QtGui .QDi alog. __ i ni t __ (self, parent)
self.myWidget = MyWindow.MyWindow()
self.myWidget. vbox . setMargin (O)
self.button = QtGui . QPushButton ( "& e
mainBox = QtGui .QVBoxLayout()

11.

" )

mainox . addWidget(self.myWidget)

malnBox . addWidget {se lf .buttonJ


self . setLayout(mainBoxi
self .connect (self .button, QtCore .SIGNAL( "clicked (} " ) ,
self.on_clicked)
def on_clicked{self):
self.myWidget.label.setText("Hoa

" )

self.button.setDisaled(True)

if

=::: " main "


n
import sys
= QtGui .QApplication(sys .argv)
window = MyDialog()
window.setWindowitle("peyeco -" )

window . resize(OO, 100 )


wi ndow. show ()
sys.exit (app.exec_())

test.pyw

(.

19.7). n

t n n n .

n - n t .

19.7.

,)

MyDialog,

19.4

QDialog.

. ,
n-- n .

MyWi ndow myWidget:

sel f .myWidget = MyWindow.MyWindow( )



, n n:

self .myWidget . vbox.setMargi n{O)

MyWindow.

19. PyQt

371

MyWindow ,

self .connect (self .button, QtCore. SIGNAL ( "clicked () "),


self .on_clicked)
.

on_clicked(), (
setext ()) ( setDisaed () ).
on_ clicked () self,
MyDialog, MyWindow.
.

.
,
:

if

name

== "

main

":


. ,
, . , . .

19.4

- . ,
, -
.
, .

19.5.

Visual Studio

Qt

Desiger
Delphi,

. .
.
,
.

. PyQt Qt

Designer,

19.5.1.

v4.8.3 for Python v3.2


. 19.8.

Qt

Desiger 1 PyQt

GPL

(86) 1 Designer. ,

Widget

,
.
.

Display Widgets

Label

372

11.

n n , n n . n
<?n n

Push Button

n . n

n , n n
n n 1
. , n n

1 .

Ffiaen ~Awer~1'
-.
.~.....

:; L
=

~fl;:

\lertlclllt~

l'ottzontol Loyoo.t

Dloloo wth e..ttons 8attom


Dloloo ..th e..ttons RJoi>t

Gridt~
1~

formL~
r;:=-- Sptc
. . . t'ottzontol Scet

OioloQ ~ tons
j

anw.>e~ow

WldQot

.1 _.,59. .
EJ PIJ<ho.tton

1JW<ooiicro

~~

QOod<Widoet

Qffl!ltWJ
QGr>IIox

QScrniAru
QdAru

~ Todo.tton

QToWidQot

!i)

Radio ftQn

Chod<ox

C"""""""t.nke..tton

!tn

QTcdJox
QSt-.dget

QWI>..d
QWI>or<S'*

~1t ~.e,-,;,e:t'IX yc'();'k'ta


YctpOikoo>

u.t-

"':8 Tree..,...
fI ...,...
JIDeoum..,...
~;:g

...,".

/1 -;;._~- ....
1

~~

..i

----

!tpm 1/&it l!lp!ttl!oiiij

[lu.tllo'od9et

":8 Treo WldQot


IEJ . Wldvot
.

19.8. Qt Designer

(.

19.9) n .
objectName yrorm.
geometry , .
300, 70 ( . 19.10).
. , ,

windowTitle.
n, n n
.

objectName

l abel,

text

n,

373

19. PyQt

alignment Aligncenter. n
objectName btnQuit. text

n
.

. .

ti.lt1pi14

.:

,..,."'-:. ~-

IUJ.I Form
6 ~ ...

~ Q't'oxlayout

...

8~on

t~d.:~~

lt! .. sizeP_oic.Y..

.J

(Prefeed, Prefe ...

mlnrnum~e.

\~ :.rxirrun5.il~

size!ncrement
.rt
''
.....
.
~

... ~ Qt~el

300
71J

~ s512
~tt_e
~-

1677ntsx 1677 ..

_.~

forJt

<-1
.

19.9.

19.10.

.
n

MyForm.ui .

- n

Qt

Designer, n .

19.5.2.

ui-

, ui- L-,

Python.

, n n

impor t

n. n ui- n , n

uic, PyQt.

, n :

f rom PyQt4 import uic


ui- n
loadU i(<ui -a>( ,

loadUi ( >. :

<n >])

, .
n n n , n,

Destgner objectName.

19.5). n Qt

374

11.

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui, uic


import sys
= QtGui.QApplication(sys.argv)
window = uic .loadUi ( "MyFonn. ui")
QtCore.QObject.connect(window.btnQuit, QtCore.SIGNAL("clicked()"),
QtGui.qApp.quit)
window. show ()
sys.exit(app.exec_()}
,

self ( 19.6).

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui, uic

class MyWindow(QtGui.QWidget):
def
init (self, parent=None):
QtGul.QWldget. init (self, parent)
uic.loadUi ( "MyFonn. ui", self)
self .connect (self .btnQuit, QtCore. SIGNAL ( "clicked () "),
QtGui.qApp.quit)
if

name
main "
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

ui- loadUiType ().


: .
, ,

self

setupUi (}

19.7).
.~:~~"~".''<!-!''.'.:"~'~'-'"-!:''"'"':"~'"""'"""~~~:'"''~'~".''"~"'''''''"''"'""'"'""~

p~tt1;.1'

.'

,!

~~;;;;~; ... ;~~~.;~;;,.,;;;,.,.;;' .:.:;;.= ~: = ; . . . . . . i....... :...........'.i .......... ,;.,, ... ,;........;J

, : . . .

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui, uic

class MyWindow(QtGui.QWidget):
def
init (self, parent=None}:
QtGui.QWidget. init (self, parent)
Fonn, Base = uic.loadUiType("MyFonn.ui")

19. PyQt

375

self.ui = Form()
self.ui.setupUi(self)
self.connect(self.ui.btnQuit, QtCore.SIGNAL("clicked()"),
QtGui.qApp.quit)
if

n
main
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

ui- ,
. .
u
(

MyWindow

19.8).

Form, Base = uic.loadlJiType("MyForm.ui")


class MyWindowiQtGui.QWidget, Form):
def
init lself, parent=None):
QtGui.QWidget. init lself, parent)
self.setupUilself)
self.connectlself.btnQuit, QtCore.SIGNAL("clicked()"),
QtGui.qApp.quit}

19.5.3.

ui- -

ui-

ui- -

pyuic4.bat,

Python.

C:\Python32\Lib\site-packages\PyQt4\i.
, ui-. u :

pyuic4.bat MyForm.ui

ui_MyForm.py

ui_MyFom.py,
u

import. Ui _ MyForm : setupUi 1)


retranslateUi 1}. u
n , setuplJi 1)

19.9).

l:'~-~~~~~:;19~9;~~~~~~:;;~;~~~~~::~~~;;~1

t.; : .... :..................... ;.;,,,,,.,.;;,,,,,, . ;.:,..~ ........ ;:.-:.~ ........ ;;~;,;;~ .. ; ......; ... :; ....... ~.:;.~ ..:;.'..~.,;:.~;;;,.;;i~~:];;;:~~.... ;;;,:,,

# -*- coding: utf-8 -*from PyQt4 lmport QtCore, QtGui


import sys, ui_MyForm
= QtGui.QApplication(sys.argv)
window = QtGui.QWidget()

..... ..

376

11.

ui ~ ui~MyForm.Ui~MyForm()
ui.setupUi(window)
QtCore.QObject.connect(ui.btnQuit, QtCore.SIGNAL("clicked()"),
QtGui.qApp.quit)
window. show ()
sys.exit(app.exec~())

-
,

setupUi () self ( 19.1 0).

:.. ,, ... ,... ,,.,:.~,,;:,,;:~.-:::~;.::."::"'''.'"'.".'''':~.:::::::. .. :.:.. :.'.''.'.''''"~':::::".:;:~~"'"'''''.'''""'"'"''~~"'"'''"~''t''''''"'''''''''.''"''''.:;"''''''''"''''.'' ., ...... " .. ,,, .. ,",:

1...~.~~~~-~-~--~!::.~?..~ ~.~.~~~..~.~~~-~:~;.~~:S~~--~-~~-~~: ~~-~~~-~:.~:


# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui
import ui~MyForm

. . . . . . . . . . . . . . . . ,..............................................................................J

class MyWindow(QtGui.QWidget):
def
init (self, parent~None):
QtGul.QWldget. init (self, parent)
self.ui ~ ui~MyForm.Ui~MyForm()
self.ui.setupUi(self)
self.connect(self.ui.btnQuit, QtCore.SIGNAL("clicked()"),
QtGui.qApp.quit)
n
main
import sys
~ QtGui.QApplication(sys.argv)
window ~ MyWindow()
window. show ()

sys.exit(app.exec~())

MyWindow

19.11).

r:::~~~~~~:~ ~:~j:~::::~~~~j~~~~:~!::~~~~~::~~~~t.~;:~~~~~;~_::.::.:::::::.:;:::::.:::.:::.::.:.:: ::.:::.:::::::;:::.:.::::::::::.:::::.<:::::::::::::::::::::::.::..:::J


class MyWindow(QtGui.QWidget, ui~MyForm.Ui~MyForm):
def
init (self, parent~None):
QtGui.QWidget. init (self, parent)
self.setupUi(self)
self.connect(self.btnQuit, QtCore.SIGNAL("clicked()"),
QtGui. qApp. quit)
,

PyQt

, ,

ui-

pyuic4.bat.

. ,

, .

Qt

" .

Designe. "

19.

19.6.

377

PyQt

PyQt

PyQt

, PyQt4:

QtCore- , .
;

QtGui- , , , , , .;

+ QtSql- SQLite, MySQL .;


+ Qtsvg- (SVG);
+ QtOpenGL- OpenGL;
+ QtNetwork- , ;
+ QtWebKit- L-;
+ phonon QtMultimedia-:- ;
+ QtXml QtXmlPatterns- n L;
+ Qtscript QtScriptTools- Qt Script;
+ Qt- .

QAxContainer, QtTest, QtHelp

PyQt4 QtDeclarative,

QtDesigner.

~ :

from PyQt4 import

< >

QtCore QtGui:

from PyQt4 import QtCore, QtGui


QtCore QtGui.
, .

19.7.

PyQt

PyQt Qt,. ++.


Qt ,

++. , ,
. ++,

Python

, . .

.
, :

QString- Unicode-cpoa. ! 2 ( )
str . , !

\.

sip, setapi () :

> import sip


>>> sip.setapi('QString', l)
>>> from PyQt4 import QtCore

378
>>> 5
>>> 5

11.

= QtCore.QString("cpoa")

PyQt4.QtCore.QString('cpoa')

> 5tr(5)
''

QChar- Unid-. API 2 ( )


5tr. , API 1.
:

>>> import 5ip


>>> 5ip.5etapi('QString', 1)
>>> from PyQt4 import QtCore
>>> QtCore.QChar("a")
PyQt4.QtCore.QChar(Ox0061)

QStringLi5t- Unicode-cpo. API 2 ( )


. ,

1.

API

> import 5ip


>>> 5ip.5etapi('QString', 1)
>>> from PyQt4 import QtCore
>>> L = QtCore.QStringLi5t(["51", "52"])
>>> L
<PyQt4.QtCore.QStringLi5t object at Ox00FD8618>
> li5t (L)
[PyQt4.QtCore.QString('51'), PyQt4.QtCore.QString('52')]
>>> [5tr(5) for 5 in li5t(L)]
['51', '52']

QByteArray- . byte5. :
>>> from PyQt4 import QtCore
>>> arr = QtCore.QByteArray(byte5 ("5tr", "cpl251"))
>>> arr
PyQt4 .QtCore.QByteArray (' 5.tr')
>>> byte5(arr)
b'5tr'

QVariant -

API.

1,

. , :

Python

QVariant,
toPyObject (). ,

. :

> import 5ip


>>> 5ip.5etapi('QVariant', 1)
>>> from PyQt4 import QtCore
>>> n = QtCore.QVariant(10)
>>> n
<PyQt4.QtCore.QVariant object at Ox00FDBD50>
>>> n.toPyObject()
10

19. PyQt

379

>>> QtCore.QVariant() #
<PyQt4.QtCore.QVariant object at Ox00FD8420>

API

( )

. ,

QVariant API

TypeError:
>>> from PyQt4 import QtCore
>>> QtCore.QVariant(lO) # ~n
... n ...
TypeError: PyQt4.QtCore.QVariant represents
and cannot instantiated

mapped type

QVariant, .

Python.

QPyNullvariant. Qt
(, "QString") Python (, str).
isNull (), True.
typeName (). :
>>> from PyQt4 import QtCore
>>> nullVariant = QtCore.QPyNullVariant(int)
>>> nullVariant.isNull(), nullVariant.typeName()
(True, 1 int 1 )
> nullVariant = QtCore.QPyNullVariant ("QString")
>>> nullVariant.isNull(), nullVariant.typeName()
(True, 1 QString 1 )

),

API

QDateTime

QDate ( ), QTime (
QUrl

( ), QextStream ( )

(URL-apec).

19.8.


l(
. _ () .

, ,
. ,

quit ()

exit ( [returnCode=OJ).

, - ,
.

n .

setQuitOnLastWindowClosed()

QApplication

.

. ,
.

sleep () time ( 19.12).

380

11.

:-"'' .......... ~ ........ ~ ...~ ...... ' ................ ~~ ~' .....~. ......... , ......... ~ ............... , , .... ~~ ~~ .. '"~':'""~ ~: '.' '''.''~,~ '.< ::.

[ .19.12:nitlt ;rt:!n~:oilb.:4>n&pait .
;,.~

.... :.........:.......... :::.::::.:.:.; .. :...........~.: ....;;.~ ...:.........~.;;;;.",,,;,;;,;:~:::~.:: .. :....;;,;;;,;';~;; ...~ . ::..:..:;

# -~- coding: utf-8 -~from PyQt4 import QtCore, QtGui


import sys, time

def on clicked():
time.sleep(10) #

"m"

10

= QtGui.QApplication(sys.argv)
button = QtGui.QPushButton("ayc ")
button.resize(200, 40)
QtCore.QObject.connect(button, QtCore.SIGNAL("c1icked()"),
on clicked)
but ton. show ( 1
sys.exit(app.exec_())

on _ clicked (),

""

. , ,

. , .

19.11.

,
,

. ,
r, ,
.

19.11.

processEvents ( [ flags=AllEvents])

20

QCoreApplication.

19.13) .

.............................
~ 19>t. :I'J~l!

?.~ ;.......... '... ;, .. ~ .. :;, :... '' .. :.; .: ......... ,;; . ,;, .~:.': ..'.'. :. ,;, ;.::... ;, .,~.:. : , ;:;:.=; ;:, :

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys, time
def on clicked():
button.setDisaed(True)

for i in range(1, 21):


QtGul.qApp.processEvents()

19.

381

PyQt

time.sleep(l)
print("step -", i)
button.setDisaed(False)

"m"

= QtGui.QApplication(sys.argv)
button = QtGui.QPushButton("ayc ")
button.resize(200, 40)
QtCore.QObject. connect (button, QtCore. SIGNAL ( "clicked () "),
on_clicked)
but ton . show ( )
sys.exit(app.exec_())

nt? n n. n
n n n. n n n
n n. , n

n-n , .

19.9.
n

no

n. n n

n. n

processEvents ()

processEvents ()

n n. n n

n n . n
n n. n
, n n

no

GUI-nooa,
n n. n n

n.

19.9.1. QThread.
n

<>

Qhread

PyQt

QThread

QThread, QObject.

( [parent=None])

n n, ,
Qhread, n

run ().

, n

run (),
run () n n
start (),

n. n
. n

n n n
n

run (),

run (). ,

n GUI-nooe, n

. , n n, start (),

run () .

start ()

start([priority=Qhread.InheritPriority])

priority n n n no n.

, n n n n

n n n n -

382

11.

. ( )
QThread:

+
+
+
+
+
+
+

Id1ePriority- ;

1 - LowestPriority;
2 - LowPriority;
3 - Nona1Priority;
4 - HighPriority;
5 - HighestPriority;
-

TimeCritica1Priority- ;

7 - Inheri tPriority- (
).

setPriority ( < >).


priority ().

started (), -

finished (). ,
u . ,

True,

isRunning () isFinished (). isRunning ()

isFinished ()

True,

u n
. , - GUI-,
, . GUI-
.

emit ()

. , n
, .
- GUI-.
QThread (

19.14).

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


c1ass MyThread(QtCore.QThread):
def
init
(se1f, parent=None):
QtCore.QThread. init
def run (self) :
for i in range(l, 21):
self.s1eep(3)

(se1f, parent)

"m"

self.emit(QtCore.SIGNAL("mysigna1(QStrg)"),

c1ass MyWindow(QtGui.QWidget):
def

init
(se1f, parent=None):
QtGui.QWidget. init
(se1f, parent)

"i = 'ts"

i)

19.

383

PyQt

self.label = QtGui.QLabel("Hae . ")


self.label.setAlignment(QtCore.Qt.AlignCenter)
self.button = QtGui.QPushButton("ayc ")
self.vbox = QtGui.QVBoxLayout()
self.vbox.addWidget(self.label)
self.vbox.addWidget(self.button)
self.setLayout(self.vbox)
self.mythread = Myhread()
#
self.connect(self.button, QtCore.SIGNAL("clicked()"),
self.on_clicked)
self.connect(self.mythread, QtCore.SIGNAL("started()"),
self.on_started)
self.connect(self.mythread, QtCore.SIGNAL("finished()"),
self.on_finished)
self.connect(self.mythread, QtCore.SIGNAL("mysignal(QString)"),
self.on_change, QtCore.Qt.QueuedConnection)
def on_clicked(self):
self.button.setDisaed(True)
#
self .mythread. start ()
#
def on_started(self):
#
self.label.setText("Ba on_started()")
def on_finished(self):
#
self.label.setText("Ba on_finished()")
self.button.setDisaed(False)

def on_change(self, s):


self.lael.setText(s)

if

n
main "
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window.setWindowitle("cooae Qhread")
window.resize(OO, 70)
window. show ()
sys.exit(app.exec_())

, Myhread,

QThread,
run (). run ()
for sle~p (). \)
mysignal (QString) i.
MyWindow :

self.connect(self.mythread, QtCore.SIGNAL("mysignal(QString)"),
self.on_change, QtCore.Qt.QueuedConnection)
Myhread (
~

MyWindow mythread),
connect ()
emi t ().

. ,

, . -

384

11.

setext

().

connect () QueuedConnection , n

n, . . GUJ-. GUI-

MyWindow ,

n . n

Myhread mythread.

n started (), finished ()


mysignal (QString). start ()

. ,

setDisaed ().
n finished ( J .
, n

sleep () QThread, sleep () time.


sleep () -

QtCore.QThread.sleep(3)

"m"

msleep () - ~:
QtCore.QThread.msleep(3000)

QThread:

"m"

,1

usleep ( J - :
QtCore.QThread.usleep(.3000000) #

19.9.2.

"m"

,1

. ,

run (). .

. n , , n , ,
. n

. .
, n clicked ()
.
.

19.15.

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class Myhread(QtCore.QThread):
def
init
(self, parent=None) :
QtCore.QThread. init (self, parent)

19.

385

PyQt

self.running
False
#
self.count =
def run(self):
self.running
True
while self.running:
#
self.count += l
self .emit (QtCore .SIGNAL ("mysignal (QString) "),
"count
%s" % self.count)
self.sleep(l)
#
class MyWindow(QtGui.QWidget):
def
init (self, parent=None):
QtGui.QWidget."_init (self, parent)
self.label = QtGui.QLabel("Hae n ")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.btnStart = QtGui.QPushButton("ayc ")
self.btnStop = QtGui.QPushButton("Ocao ")
self. vbox = QtGui ..QVBoxLayout ()
self.vbox.addWidget(self.label)
self.vbox.addWidget(self.btnStart)
self.vbox.addWidget(seif.btnStop)
self.setLayout(self.vbox)
self.mythread = Myhread()
self.connect(self.btnStart, QtCore.SIGNAL("clicked()"),
self.on_start)
self.connect(self.btnStop, QtCore.SIGNAL("clicked()"),
self .on_stop)
self .connect (self .mythread, QtCore.SIGNAL ("mysignal (QString) "),
self.on_change, QtCore.Qt.QueuedConnection)
def on_start(self):
if not self.mythread.isRunning():
self .mythread. start ()
#
def on_stop(self):
self.mythread.running = False #
def on_change(self, s):
self.label.setText(s)
def closeEvent(self, event):
#
self. hide ()
#
self.mythread.running = False #
self.mythread.wait(5000)
# ,
event. accept ()
#
if

name
main "
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window.setWindowitle("ayc
window.resize(OO,

100)

windo-:. show ()
sys.exit(app.exec_())
13

1349

")

386

11.

n Myhread running n

False. n n run ( 1
True. n . '\
. False, .

MyWindow n n, n

n Myhread. . n
n

on_ start ( 1,

isRunning ( 1 n n n. n Jn,
n n n n start ( 1. n
n n on_ stop ( 1, running n
False. run ( 1.
n n

, n . n
- , n ,

n. n n n , n

terminate ( 1. n , . . n

n .
. , n , n n
n.

terminate ( 1 wait ( 1.

n . n
n n. n n ,
n n. n
, nn ,
closeEvent ( 1. n n
n . n n event.

n n .
closeEvent ( 1, accept ( 1 .
n ,

ignore ( 1.

closeEvent ( 1 n running False. n

wai t ( 1 n .
n

wait ( 1

n ,

no

n . ,

. n , n .
wait ( 1 True, n n , False n . n ,
n-n . n

closeEvent ( 1.

hide 11.

n . n
n _

(1.

. n , quit ( 1 exit ( [returnCode=O]


n n (

l 19,111~ (;).t ~~.Ji~~~~:~~,~~i


; . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .: : . ; ; . .=. . .

~:.:;; . . . -..... ~:. . . . .. . ;:.:~;;,,;;,:;,::,:,:;~..;;";;,;,,,, . . . . . . .

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui

19.1 ).

1.

19.

387

PyQt

class Threadl(QtCore.Qhread):
def
init (self, parent=None):
QtCore.Qhread.
init (self, parent)
self.count =
def run (self) :
self ._ ()
#
def on_start(self):
self.count += 1
self.emit(QtCore.SIGNAL("sl(int)"), self.count)

class Thread2(QtCore.Qhread):
def
init (self, parent=None) :
QtCore.Qhread.
init (self, parent)
def run(self):
self ._ ()
#
def on_change(self, i):
i += 10
self.emit(QtCore.SIGNAL("s2(const QString&)"), "%d"% i)
class MyWindow(QtGui.QWidget):
def
init (self, parent=None):
QtGui.QWidget. init (self, parent)
self .label = QtGui.QLael (" n")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self. button = QtGui. QPushButton ("
self.vbox = QtGui.QVoxLayout()
self.vbox.addWidget(self.label)
self.vbox.addWidget(self.button)
self.setLayout(self.vbox)
self.threadl = Threadl()
self.thread2 = Thread2()
self.threadl.start()

")

self.th~ead2.start()

self.connect(self.button,

QtCore.SIG~AL("clicked()"),

self.threadl.on~start)

self.connect(self.threadl, QtCore.SIGNAL("sl(int)"),
self.thread2.on_change)
self .connect (self. thread2, QtCore.SIGNAL ("s2 (const QString&) "),
self.label, QtCore.Sim("setText(const QString&)"))
if

n
main "
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. setWindowi tle ("
window.resize(OO, 70)
window. show ()
sys.exit(app.exec_())

n")

388

11.

Threadl, Thread2 MyWindow.


run ()
_ (); . MyWindow
, Threadl Thread2.

on_ start ()

. - (

count), emit ()
sl (int) . sl (int)

on_ change () .
- , s2 (const QString&)
.

s2 (const QString&)
setText (const QString&) . , ~
on_ start () Threadl,
on_ change () Thread2,

19.9.3.

queue.

.
, ,
. , ? ,
? , ,

.
.
, ,

.
, , , I!

- . , ?

queue,

Python,

. ,
. :

Queue _____: ( , ). :
<>=

Queue([maxsize=O])

>>> import queue


>>> q = queue.Queue()
>>> q.put_nowait ("eleml")
>>> q.put_nowait ("elem2")
>>> q.get_nowait()
1
eleml 1
>>> q.get_nowait()
1
elem2 1

LifoQueue- ( , ). :
<>=

LifoQueue([maxsize=O])

19.

PyQt

389

>>> q = queue.LifoQueue()
>>> q.put_nowait("elem1")
>>> q.put_nowait ("elem2")
>>> q.get_nowait()
'elem2'
>>> q.get_nowait()
'eleml'

PriorityQueue- n. n
n:r ( n n ).
, n

, n, - . :
<>=

PriorityQueue([maxsize=O])

>>> q = queue.PriorityQueue()
> q.put_nowait( (10, "eleml"))
>>> q.put_nowait ( (3, "elem2"))
>>> q.put_nowait ( (12, "elem3"))
>>> q.get_nowait()
(3, 'e1em2'1
>>> q.get_nowait()
(10, 'elem1')
>>> q.get_nowait()
(12, 'elem3')

maxsize ,

. n ( )
, .

n :

put (<> [,

ock=True J

[,

timeout=None J ) -

n k True, .
. n

timeout
queue. Full;

. ,

put _ nowait (<>) - . :


ut(<>,

False)

get ( [lock=True] [, timeout=None])- .


n k rue, n n
. n timeout .
. n, queue.Empty;

+
+

get _ nowait () - get ( False);


join ( 1 -

n, n .

n n . task _ done ().


, n ;

task _ done ( 1 - n. n ;

390

qsize () n

/1.

n .

n,

+
+

empty ()

full () -

True,

n,

True,

False-

n ;

False-

n (

19.17).

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import queue

class MyThread(QtCore.QThread):
def
init (self, id, queue, parent=None):
QtCore.Qhread.
init (self, parent)
self. id = id
self.queue = queue
def run (self) :
while True:
task = self.queue.get()
#
self. sleep (5)
#
self.emit(QtCore.SIGNAL("taskDone(int, int)"),
task, self.id)
#
self.queue.task_done()
class MyWindow(QtGui.QPushButton):
def
init (self):
QtGui.QPushButton. init (self)
self .setText (" ")
self.queue = queue.Queue()
#
self.threads = []
for i in range(l, 3):
#
thread = Myhread(i, self.queue)
self.threads.append(thread)
self.connect(thread, QtCore.SIGNAL("taskDone(int, int)"),
self.on_ta~k_done, QtCore.Qt.QueuedConnection)
thread. start ()
self. connect (self, QtCore. SIGNAL ("clicked () "),
self.on_add_task)
def on_add_task(self):
for i in range(O, 11):
self.queue.put(i)
#
def on_task_done(self, data, id):
print (data, "- id =", id)
#

if

19.

PyQt

391

"

import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. setWindovi'Ti tle ("
window.resize(OO, 30)
window. show ()
sys.exit(app.exec_())

queue")

Myhread (id)
(queue), .
run()

get (). , , ~:<


. ( ),
taskDone (int,

int). task_ done () ,


.
MyWindow. ,

QPushButton ( ), QWidget.

QWidget, ,
, . ,

QPushButton.

MyWindow setext ()
. Queue queue.
,

. (
) .

taskDone ( int,

int) start ().

.
on_add_task(),
.

taskDone (int,
int)
task_done (), .
on_ task_ done (),

. J! GUI-,
, , .
. ,
,

pyw.

. , .

19.9.4.

QMutex

QMutexLocker

,
. .


.
.

392

11.

PyQt n QMutex
QtCore. QMutex :
<>=

QMutexLocker

QMutex([mode=QtCore.QMuLex.NonRecursive])

mode n NonRecursive (n

n ; n n
; )

Recursive (n n ~
unlock ( 1

; n ,

). , n
:

lock ( 1 - . n,
n n ;

tryLock ( [< >]) - .


n , True.
n, False
.
n. n ,

tryLock ()

lock ();

unlock () - .

QMutex (

19.18).

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyThread(QtCore.QThread):
= 10
#
mutex = QtCore. QMutex ()
# r
i
def
lnit (self, id, parent=None):
QtCore.QThread. init (self, parent)
self.id = id
def run (self) :
self. change _ ()
def change_x(self):
Myhread.mutex.lock()
,, #
print("x =", Myhread.x, "id -" self. id)
Myhread.x += 5
self. sleep ( 2)
print("x =", Myhread.x, "id -" self. id)
Myhread.x += 34
print ( " =", Myhread.x, "id -" self. id)
Myhread.mutex.unlock()
#
class MyWindow(QtGui.QPushButton):
def
liL
(self):
QtGui.QPushButton. init (selfl
slf.stt!"")

19.

393

PyQt

self.threadl = MyThread(1)
self.thread2 = MyThread(2)
self.connect(self, QtCore.SIGNAL("clicked()"), self.on_start)
def on_start(self):
if not self.thread1.isRunning(): self.thread1.start()
if not self.thread2.isRurining(): self.thread2.start()
if

main

"

irnport sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window.setWindowitle("cnooae
window.resize(OO,

Qutex")

30)

window. show ()
sys.exit(app.exec_())
Myhread ,
.
. ,

. ,

, Myhread Qutex

mutex. ,
, . ,
, .

change_ (), ,
lock () unlock (). ,
change_x ()

MyWindow

Myhread . n
_

start (),

, , ' .
:

=
=
=
=
=
=

10
15
49
49
54
88

id = 1
id = 1
id
1
id
2
id
2
id
2

1, 2. ,
:

= 10 id

- 15 id

=2
= 20 id = 1
= 54 id = 1

394

54 id
= 88 id

2
2

11.

n 2 JI
n change _ () n 1.
change_x()
, . . n n unlock (). ,

unlock ()

no

, n .

n n QMutexLocker. n

.
, .
, n

QMutexLocker , n

Myhread n QMutexLocker (

change_ ()

19.1 9).

def change_x(self):
ml = QtCore.QutexLocker(Myhread.mutex)
print("x =", Myhread.x, "id =", self.id)
Myhread.x

+= 5

self. sleep ( 2)
print ( " =", Myhread.x, "id -"
Myhread.x

self. id)

+= 34

print("x =",

Myhread.x,

"id -"

self.id)

n QMutexLocker n

++

Python.

++ .

, n , .
, n n, n,

if, n n :

if

()

int

{
10;

//

11 ...
}

1/

Python

. n

n, n :

if

= 10
# ...

, . QMutexLocker

PyQt

Python

n n

, n

wi th ... as. n , n

19. PyQt

395

wi th ... as. change _ ()


with ... as ( 19.20).

Myhread


''~"!'.'.,...'.'''''"

''" '''""" ''''""' <""",,.,., '''"''"" ' " .. "'''"'~" ''"'' "''''''' ,>> ~ ..,, ~ ... ,"''''"'."'''''''""~-~''~'~ ... , "'''~""~~~ ..... ~'"" >>><~ ''' '' '" ''" '+-"' '''' '" "''" ~'" "

' '''' ; '''

">

:I,ictttr.19.2Q: n.f.,~t ttpy~..Jt wl1;h,> :~


......... ....................................... ................ .............. ........... ...................................................................... ............................................................................................. :
~

def change_x(self):
with QtCore.QMutexLocker(Myhread.rnutex):
print("x =", Myhread.x, "id =", self.id)
MyThread.x += 5
self.sleep(2)
print("x =", Myhread.x, "id -" self.id)
MyThread.x += 34
print("x =", Myhread.x, "id -"
- ' self. id)
#
, ,
. n ,

n. n
n n n. n
, n, n .

n GUJ-nooa.
GUJ-noo, n n .
n , n n. n
,;. n n, , n
n , n, , n n

, n .

n n
n .

QSernaphore
QWai tcondi t ion.

PyQt, , C:\Pytho32\Lib\site
packages\PyQt4\examples\threads. ,
Pytho rnultiprocessing threading,
. PyQt n
QThread, . . .

19.10.

n n

. n -, n
. -

n. -

QtGui.

PyQt

QSplashScreen

<>

QSplashScreen((<opaee>]

<>

QSplashScreen(<Poe>[,

[,

flags=<Tn

<>][,

>])
flags=<Tn

>])

<> n n. n

<> (n

QPixrnap),

396

.
.

WindowstaysOnTopHint.

+
+

QPixmap

n n

n n , n,

QSplashScreen

show 1) finish

flags

11.

(<

>)

n;

showMessage (<> [,

<>

[,

<>]

]) -

n n n . n
.
n

1: AlignTop (no ), AlignCenter (no


AlignBottom (no ), AlignHCenter (no ),
AlignVCenter (no ), AlignLeft (no ), AlignRight (no n

),

). n .

n

QColor

QtCore.Qt
(n,

(n, k

(no ), white . .)
QColor("red"), QColor("#ffOOOO"), QColor(255, ,

0) .);

+
+

clearMessage 1)

- n;

stim(<>)- n . n
n

pixmap 1)

QPixmap;

- n

QPixmap.
19.21.

~..... .:...~....~:,..~~;:~9:~1:fi~;~a;t~~i~~,,:

,,;,,,,;,.;;,,,;:;,;:.:.;;,...;;i ...;,,,..:,,,,.,"''" . ;.:....... ":;....~.= :~=~;;_,,,;:;,,,, :.....,;:;;;:;;

# -*- coding: utf-8 -*from PyQt4 import QtGui


from PyQt4.QtCore import Qt, SIGNAL
import time

class MyWindow(QtGui.QPushButton):
def
init (self):
QtGui.QPushButton. init (self)
self. setText (" ")
self.connect(self, SIGNAL("clicked()"), QtGui.qApp.quit)
def load_data(self, sp):
for i in range(l, ll):
#
time.sleep(2)
# -
sp. showMessage (" . . . {)%". format ( i * 10) ,
Qt.AlignHCenter 1 Qt.AlignBottom, Qt.lack)
QtGui.qApp.processEvents() #
if

main

"

import sys

splash

QtGui.QAppli~ation(sys.argv)
=

QtGui.QSplashScreen(QtGui.QPixmap("img.png"))

19.

PyQt

397

splash. showMessage (" ... 0%",


Qt.AlignHCenter 1 Qt.AlignBottom, Qt.ack)
splash.show()
#
QtGui.qApp.processEvents()
#
window = MyWindow()
window.setWindowitle("cooae QSplashScreen")
window.resize(OO, 30)
window.load_data(splash)
#
window. show ()
splash.finish(window)
#
sys.exit(app.exec_())

19.11.

PyQt

600 .
PyQt 600 .

, , , .

PyQt,

, .
, . ,
.

www.riverbankcomputing.eo.uk/.

HTML

http://

C:\Python32\Lib\site-packages\PyQt4\doc\html. ,
index.html. classes.html,
- modules.html.
.

PyQt4\examples.

C:\Python32\Lib\site-packages\

20

QWidget. QWidget
- QObject QPaintDevice. QWidget
, , ,
. QWidget

. , ,
, , .
,

, , ~1 ,

.
QWidget
, QWidget, QFrame (
) QDialog ( ). QDialog
( )

QMainWindow, ,
. QDialog QMainWindow ,
.

20.1.

20.1 .

... ,.... ,. ................................................... """'""''"'''"'''"''""''"'''"'''"'''"'''"'''"'''"'''"'""'''"'""'''"'''"'''"'''"'''"'''"'''"'''"'''"'""'''"''" .._,, ............................ ,, .. ,., ............. ,............. ..


[ ~tlt 2;1; li~t~&
.....
. .
;,,,,,,,,,,,,~,,;,~,,:,,;, ..~ .....,.;,:,:;,:;,.,,,,,;,,;,,,~ ....~~:~.~'.. ;,;,.,,,,;,,,~ ;.~,.,;,,,,,,.,;;.,;;,,;,,;,;;,,.,;,~;.,;;~,;-,;,;~,,;;~).. ,;,;,;,;,:;;;,;~;,',;;;~ .. ,,,;,,,,,,,,,,,,,,,,.,,,,.,,,,,,,,,,,,,,.,,.,,,,,,

# -*- coding: utf-8 -*from PyQt4 import QtGui


import sys
.= QtGui.QApplication(sys.argv)
window = QtGui.QWidget()

window.setWindowitle("aooo ")

window.resize(300, 50)
window. show ()
sys.exit(app.exec ())

20.

399

QWidget :
<>= QWidget([parent=<Poe>]

[,

flags=<Tn >])

.n parent n. n
None, n .

n flags n , n, ,
, n . , ,

, . , .

flags,

setParent ( ) . :
strnt(<>[,

<n >])

parentWidget ().

None.

setWindowitle ().
:

setWindowitle(<Tec,

>)

show (),

. hide ().
setVisie (<>).

True, ,
False, . :
window.setVisile(True)

, , isVisie ().

rue, , False- . ,

isHidden (). True,

False-

20.2.

QWidget ,

: , , .

setWindowFlags () flags

QWidget. , setWindowFlags ()
. :
setWindowFlags(<Tn

>)

<n > QtCore.Qt:

+
+

Widget- QWidget;
Window- , , ,
. ,

, .
;

400

11.

Dialog- . ~,
n . .
:

window.setWindowFlags(QtCore.Qt.Dialog)

+
+
+

Sheet;
Drawer;
Popup- , .
. , .
;

l- , .
( , ),
. ;

ToolTip- , .
. ;

SplashScreen- , .

. .

QSplashScreen;

Desktop- , .
;

SuWindow- , , ,
. ( ,
) . .

windowype ().

QtCore .Qt 1 ( ;
):

MSWindowsFixedSizeDialogHint- .
. .ri
;

FramelessWindowHint- .
;

CustomizeWindowHint- ,
. ;

Windowitleint- .
, :

window.setWindowFlags(QtCore.Qt.Window 1
QtCore.Qt.FramelessWindowHint
9tCore.Qt.WindowitleHint)

+
+

WindowSystemenuint- ;
WindowinimizeButtonHint- ,
- ;

WindowaximizeButtonHint

~ ,

20.

+ WinctowMinaxButtonsHint -

401

WindowCloseButtonHint- n ;

WindowContextHelpButtonHint- n . n
;

WindowStaysOnTopHint- , n
;

Windowstaysonottomint- , n
n .

n n windowFlags ().

20.3.

n :

resize (<>,

<>) -

n ) , , n

n , n , n .
, .
n n, n n
n n . n

QSize. :

window.resize(100, 70)
window.resize(QtCore.QSize(100, 70))

setGeometry(<X>,

<>,

<>,

<>)-

n . n

( n), n
- . n n

QRect. :
window.setGeometry(100, 100, 100, 70)
window.setGeometry(QtCore.QRect(lOO, 100, 100, 70))

setFixedSize (<>, <>) - .


n . n

. n n QSize. :

window.setFixedSize(100, 70)
window.setFixedSize(QtCore.QSize(100, 70))

setFixedWidth (<>) - no .
n ;

setFixedHeight (<>) - no .
n ;

setMinimumSize (<>,

<>) - . n

QSize. :

window.setMinimumSize(100, 70)
window.setMinimumSize(QtCore.QSize(100, 70))

402

setMinil!lumWidth (<>)

11.

setMinimumeight (<>)

setMaximumSize (<>, <>) - .


QSize. :

window.setMaximumSize(100, 70)
window.setMaximumSize(QtCore.QSize(100, 70))

setMaximumWidth (<>)

setMaximumeight (<>)

setBaseSize(<pa>,

<>)- .

QSize.

window.setBaseSize(500, 500)
window,setBaseSize(QtCore.QSize(500, 500))

adjustsize () - .
, sizeHint ().

width ()

height ()

- :

window.resize(50, 70)
print(window.width(), window.height())

size ()

QSize,

# 50 70
:

window.resize(50, 70)
print(window.size() .width(), window.size() .height()) #50 70

minimumSize () - QSize, 11 ;

minimumWidth () minimumeight () -

maximumSize () -

QSize,

maximumWidth ()

maximumeight

()

baseSize () - QSize, ;

sizeHint ()- QSize,


. , ,
;

minimumSizeint

() -

QSize,

.
, , ;

rect () -

QRect,

, . :

window.setGeometry(QtCore.QRect(100, 100, 100, 70))


rect = window.rect()
print(rect.left(), rect.top())
#
print(rect.width(), rect.height()) # 100 70

20.

+ geometry () -

403

QRect,

n. :

window.setGeometry(QtCore.QRect(100, 100, 100, 70))


rect = window.geometry()
print(rect.1eft(), rect.top())
# 100 100
print(rect.width(), rect.height()) # 100 70
n , :

+ ;
+ n .

n,

n .
;

+ n n ,
n n. n, n n
n n .

n , ,

n frameSize (). n QSize.


, n n n .
n
. n n :

window.resize(200, 70)
# ...
window. show ()
print(window.width(), window.height())
print(window.frameSize() .width(),
window.frameSize() .height())

#
# 200 70

# 208 104

n ,

frameGeometry (). , n
QRect.

n f . n
:

window.setGeometry(100, 100, 200, 70)


# ...
window. show ()
rect = window.geometry()
print(rect.1eft(), rect.top())
print(rect.width(), rect.height())
rect = window.frameGeometry()
print(rect.1eft(), rect.top())
print(rect.width(), rect.height())

20.4.

# 100 100
# 200 70
# 96 70
# 208 104

n n :

t move ( <>,

<>)

n n .

. n
n

QPoint.

404 .

/1.

:
window.mo~e(O, 0)
window.move(QtCore.QPoint(O, 0))

setGeometry ( <>,

<>,

<>,

<>)

( ),
- . ,
.

(0, 0),

. t

QRect.

window.setGeometry(100, 100, 100, 70)


window.setGeometry(QtCore.QRect(100, 100, 100, 70))

.
n,

() () -

. .
:

window.move(10, 10)
print(window.x(), window.y())

pos () -

# 10 10

QPoint,

. - .
:

window.move(10, 10)
print(window.pos() .(), window.pos()

geometry ()

.())

# 10 10

QRect,

. , ~
. :

window.resize(300, 100)
window.move(10, 10)
rect = window.geometry()
print(rect.1eft(), rect.top())
print(rect.width(), rect.height())

frameGeometry () -

# 14 40
# 300 100

QRect,

. ,
. :

window.resize(300, 100)
window.move(10, 10)
rect = window.frameGeometry()
print(rect.1eft(), rect.top())
print(rect.width(), rect.height())

# 10 10
# 308 134

20.

405

u u
.

QApplication .desktop ( 1, .

widtt1 ( 1 - :

height 11

- :

desktop = QtGui.QApplication.desktop(l
printldesktop.widthl), desktop.height()) # 1280 1024

screenGeometry 1)

QRect,

desktop = QtGui.QApp1ication.desktopl)
rect = desktop.screenGeometryl)
printlrect.left(), rect.top())
print(rect.width(), rect.height())

avallaeGeometry

() -

#
# 1280 1024

QRect,

( ):

desktop = QtGui.QApplication.desktop()
rect = desktop.availaleGeometry()
print(rect.left(), rect.top())
print(rect.width(), rect.height())

#
# 1280 994

u
... ........ ........ ........... ........ ... ..... ... .............. ...........................,... ' '' . .............. ,........ . ., ... ' .. . ............. ''''. ''

'.' ..

....... ' ......... . ..... ' ., .. .... ,.. ..... ' ..............
~

~.

'

20.2 .

... ' ..... ' ... '' ... ' .... ' .... '..

.... ;

t...~~~~~~-~--~-~~-~--~-~~-~-~..~~.r.~~~~~-~-~!n.~~?. ~2.,~!~~~!.::~~~!~~-:: . ". . . ,. . . . . . . . . . . . . . . . . . . . . . . .

# -*- coding: utf-8 -*from PyQt4 import QtGui


import sys
= QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
window.setWlndowitle("Bo

")

100)
desktop = QtGui.QApplication.desktop()
= (desktop.width(l - window.width() 1 // 2
= (desktop.height() - window.height()) // 2
window.move(x, )
window. show ()
sys.exit(app.exec ())
window.resize(OO,

width ( 1 height ( 1,

u. .

frameSize ( 1.

. u

show 11, ,

u, . ,

406
,

11.

20.3).

~~~~;2~:;;;;;;~-6~~!~~~~~:~~~;;~~~~.::: .--": .. 1
~ .......... ",,,,.,,,;,,,.,;,, .. ,,,,,,_,,,,,,.,,,,.,\,.,,,. .. ", .. .,,.,,.,,;,.,;;',;,,;;... ,,;,.,,, .... , .... ;.,.,,, .. ,~ .. ,,"''"''"''''';''",.""'""'"'""""""'"''''''"""'''''''"''"''"''"'"'"""""'""''"';,;.,,.,,.,.;,.,.,.,, ..,.,,,.,,,.,,,.",,,,,,,;.,,.,.,,.,,

# -*- coding: utf-8 -*from PyQt4 import QtGui


lmport sys
~

window

QtGui.QApplication(sys.argv)
= QtGui.QWidget()

window.setWindowTitle("Bo

")

100)
window.move(window.width() * -2, 0)
window. show ()
desktop = QtGui.QApplication.desktop()
= (desktop.width() - window.frameSize() .width()) // 2
= (desktop.height() - window.frameSize() .height()) // 2
window.move(x, )
sys.exit(app.exec_())
window.resize(OO,

i .
, I ,
, i , i :

desktop = QtGui.QApplication.desktop()
= desktop.width() - window.frameSize() .width()
window.move(x, 0)
i , . . .

Windows

. I

availaE:Geometry

().

i ,

, , , :

desktop = QtGui.QApplication.desktop()
taskBarHeight = (desktop.screenGeometry() .height() desktop.availaeGeometry() .height())
, i i
i . , i
. i .

20.5.

QDesktopWidget.

i i / J
i I ,

QSize-

QPoint, QSize QRect. QPoint


QRect- I

I,

I . I .

20.

407

QPoint, QSize

QRect

n .

QPointF, QSizeF

QRectF .

20.5.1.

QPoint

QPoint.

QtCore

n . n

n :

= QPoint ()
QPoint(<X>, <>)
<>= QPoint(<QPoint>)
<>

<>

n :

>>> from PyQt4 import QtCore


>>> = QtCore.QPoint()
> .(), .()
(0, 0)
n :

>>> = QtCore.QPoint(10, 88)


> .(), .()
(10, 88)
n n:

>>> = QtCore.QPoint(QtCore.QPoint(lO, 88))


> .(), .()
(10, 88)
n n :

+
+
+

()

() -

setx (<>)
isNull () -

setY (<>)

- ;

True,

False-

>>> = QtCore.QPoint()
> . isNull ()
True
>>> p.setX(10); p.setY(88)
> .(), .()
(10, 88)

manhattanLength ()

- :

>>> QtCore.QPoint(10, 88) .manhattanLength()


98
n

QPoint

n n

+,

+=,-(),-=,=

!=.

. n n -. ,
n

*, *=, 1 /=).

QPoint

(n

408

11.

>>> 1 = QtCore.QPoint(10, 20); 2 = QtCore.QPoint(5, 9)


>>> 1 + 2, 1 - 2
(PyQt4.QtCore.QPoint(15, 29), PyQt4.QtCore.QPoint(5, 11))
>>> 1 * 2.5, 1 1 2.0
(PyQt4.QtCore.QPoint(25, 50), PyQt4.QtCore.QPoint(5, 10))
>>> -1, 1 == 2, 1 != 2
(PyQt4:QtCore.QPoint(-10, -20), Fa1se, True)

20.5.2.

QSize

QSize.

QtCore

:
<~>

QSize()

<~>

QSiz(<>,

<~>

'Qsize (<QSize>)

<>)

.
. :

>>> from PyQt4 import QtCore


>>> s1=QtCore.QSize(); s2=QtCore.QSize(10, 55); s3=QtCore.QSize(s2)
>>> s1
PyQt4.QtCore.QSize(-1, -1)
>>> s2, s
(PyQt4.QtCore.QSize(10, 55), PyQt4.QtCore.QSize(10, 55))
:

+
+

width ()

height () -

setWidtl)(<pa>)

setHeight (<>)- :

>>> s = QtCore.QSize()
>>> s.setWidth(10); s.setHeight(55)
>>> s.width(), s.height()
(10, 55)

isNull () - True, , Fa1se-


;

+
+

isValid () True, ,
Fa1se - ;

isEmpty () ,

sca1e () -

Fa1se-

True, ( )

<n n>. .
:

sca1e(<QSize>,
s1(<>,

<n n>)
<>,

<n n>)

20.

409

< >

QtCore.Qt:

IgnoreAspectRatio- - ,
;

KeepAspectRatio- 1 - n
n;

KeepAspectRatio~yExpanding-

2-

.
,

, <
>.

KeepAspectRatioByExpanding,

KeepAspectRatio

qimage-scalig.pg,

C:\Pytho32\Lib\site-packages\PyQt4\doc\html\images.

>>> s = QtCore.QSize(50, 20)


>>> s.scale(70, 60, QtCore.Qt.IgnoreAspectRatio); s
PyQt4.QtCore.QSize(70, 60)
>>> ~ = QtCore.QSize(50, 20)
>>> s.scale(70, 60, QtCore.Qt.KeepAspectRatio); s
PyQt4.QtCore.QSize(70, 28)
>>> s = QtCore.QSize(50, 20)
>>> s.scale(70, 60, QtCore.Qt.KeepAspectRatioByExpanding); s
PyQt4.QtCore.QSize(l50, 60)

boundedo ( <QSize>)

QSize,

>>> s = QtCore.QSize(50, 20)


>>> s.boundedTo(QtCore.QSize(400, 5))
PyQt4 .QtCote.QSize (50, 5)
>>> s.boundedTo(QtCore.QSize(40, 50))
PyQt4.QtCore.QSize(40, 20)

t expandedTo(<QSize>)

QSize,

>>> s = QtCore.QSize(50, 20)


>>> s.expandedTo(QtCore.QSize(400, 5))
PyQt4.QtCore.QSize(400, 20)
>>> s.expandedTo(QtCore.QSize(40, 50))
PyQt4.QtCore.QSize(50, 50)

t transpose () .

410

11.

>>> s = QtCore.QSize(50, 20)


>>> s.transpose(); s
PyQt4.QtCore.QSize(20, 50)
n
, n

(n*,*=,

QSize n n +, +=, - (), -=, == !=.


QSize

/=). :

>>> s1 = QtCore.QSize(50, 20); s2 = QtCore.QSize(10, 5)


>>> s1 + s2, s1 - s2
(PyQt4.QtCore.QSize(60, 25), PyQt4.QtCore.QSize(40, 15))
>>> s1 * 2.5, s1 1 2
(PyQt4.QtCore.QSize(125, 50), PyQt4.QtCore.QSize(25, 10))
>>> s1 == s2, s1 != s2
(Fa1se, True)

20.5.3.

QRect.

QRect

QtCore

n .

n :

<>

QRect()
QRect(<1eft>, <top>,

<>

QRt(<

<>

QRt(< >,

<>=

QRect(<QRect>)

<>

<>,

<

<>)

>,

<>)

>)

n .

.
n

QPoint,

- n

QSize.

n n .

QPoint.

n n. :

>>> from PyQt4 import QtCore


>>> r = QtCore.QRect()
>>> r.1eft(), r.top(), r.right(), r.bottom(), r.width(), r.height()
(0,

-1, -1,

0)

>>> r = QtCore.QRect(10, 15, 400, 300)


>>> r.1eft(), r.top(), r.right(), r.bottom(), r.width(), r.height()
(10, 15, 409, 314, 400, 300)
>>> r = QtCore.QRect(QtCore.QPoint(10, 15), QtCore.QSize(400, 300))
>>> r.left(), r.top(), r.right(), r.bottom(), r.width(), r.height()
(10," 15, 409, 314, 400, 300)
>>> r = QtCore.QRect(QtCore.QPoint(10, 15), QtCore.QPoint(409, 314))
>>> r.left(), r.top(), r.right(), r.bottom(), r.width(), r.helght()
(10, 15, 409, 314, 400, 300)

20.

411

>>> QtCore.QRect(r)
PyQt4.QtCore.QRect(10, 15, 400, 300)
:

t setLeft (<1>), setX (<1>), setTop (<1>)

setY (<1>) -

. :

>>> r = QtCore.QRect()
>>> r.setLeft(10); r.setTop(55); r
PyQt4.QtCore.QRect(10, 55, -10, -55)
>>> r.setX(12); r.setY(81); r
PyQt4.QtCore.QRec~(12, 81, -12, -81)

t setRight (<2>)

setBottom(<Y2>)

. :

>>> r = QtCore.QRect()
>>> r.setRight(12); r.setBottom(81); r
PyQt4.QtCore.QRect(O, , 13, 82)

setTopLeft ( <QPoint>) - ;

t setTopRight (<QPoint>)

+
+

setBottoLeft

- ;

( <QPoint>) - ;

setBottomRight (<QPoint>) - :
>>> r = QtCore.QRect()
>>> r.setTopLeft(QtCore.QPoint(10, 5))
>>> r.setBottomRight(QtCore.QPoint(39, 19)); r
PyQt4.QtCore.QRect(10, 5, 30, 15)
>>> r.setTopRight(QtCore.QPoint(39, 5))
>>> r.setBottomLeft(QtCore.QPoint(10, 19)); r
PyQt4.QtCore.QRect(10, 5, 30, 15)

setWidth(<Illpa>), setHeight(<Bcoa>) 1-1

setSize(<QSize>)

setRect

(<1>,

<1>,

<>,

<>) -

setCoords (<1>, <1>, <2>, <2>)-


. :

>>> r = QtCore.QRect()
>>> r.setRect(10, 10, 100, 500); r
PyQt4.QtCore.QRect(10, 10, 100, 500)
>>> r.setCoords(10, 10, 109, 509); r
PyQt4.QtCore.QRect(10, 10, 100, 500)
:

moveTo (<1>,

<1>),

moveTo (<QPoint>), moveLeft

>>> r = QtCore.QRect(10, 15, 400, 300)


>>> r.moveTo(O, 0); r
PyQt4.QtCore.QRect(O, , 400, 300)

(<1>)

moveTop (<1>) -

412

11.

>>> r.moveTo(QtCore.QPoint(10, 10)); r


PyQt4.QtCore.QRect(10, 10, 400, 300)
>>> r.moveLeft(5); r.moveTop(O); r.
PyQt4.QtCore.QRect(5, , 400, 300)

+
+
+
+
+

moveRight

(<2>) moveottom(<Y2>)

moveTopLeft (<QPoint>) -

moveTopRight (<QPoint>) -

moveBottomLeft (<QPoint>)~oveBottomRight

. :

(<QPoint>) -

>>> r = QtCore.QRect(10, 15, 400, 300)


>>> r.moveTopLeft(QtCore.QPoint(O, 0)); r
PyQt4.QtCore.QRect(O, , 400, 300)
>>> r.moveBottomRight(QtCore.QPoint(599, 499)); r
PyQt4.QtCore.QRect(200, 200, 400, 300)

+
+

movecenter (<QPoint>) -

tr'ans1ate(<C >,

< >)

trans1ate(<QPoint>)-

>>> r = QtCore.QRect(O, , 400, 300)


>>> r.trans1ate(20, 15); r
PyQt4.QtCore.QRect(20, 15, 400, 300)
>>> r.trans1ate(QtCore.QPoint(10, 5)); r
PyQt4.QtCore.QRect(30, 20, 400, 300)

trans1ated (< >, < >) trans1ated ( <QPoint>) trans1ate (), QRect,

adjust (<1>,

<1>,

<2>,

<2>)

:.

>>> r = QtCore.QRect(O, , 400, 300)


>>> r.adjust(10, 5, 10, 5); r
PyQt4.QtCore.QRect(10, 5, 400, 300)

adjusted ( <1>,

<1>,

<2>,

<2>)

QRect,

adj ust (),

+
+
+

1eft () () top () () -

;
;

right () bottom () -
;

+
+

width ()

height () -

size () - QSize. :
>>> r = QtCore.QRect(10, 15, 400, 300)

>>> r.1eft(), r.top(), r.x(), r.y(), r.right(), r.bottom()


(10, 15, 10, 15, 409, 314)

20.

413

>>> r.width(), r.height(), r.size()


(400, 300, PyQt4 .QtCore.QSize (400, 300))

+ topLeft () - ;
+ topRight () - ;
+ bottomLeft () - ;
+ bottomRight () - . :
>>> r = QtCore.QRect(10, 15, 400, 300)
>>> r.topLeft(), r.topRight()
(PyQt4.QtCore.QPoint(10, 15), PyQt4.QtCore.QPoint(409, 15))
>>> r.bottomLeft(), r.bottornRight()
(PyQt4.QtCore.QPoint(10, 314), PyQt4.QtCore.QPoint(409, 314))

+ center () -

. ,

desktop

QtGui.QApp1ication.desktop()

window.move(desktop.avai1aeGeometry(_)

.center() -

window.rect() .center())

getRect () ;

getCoords ()

. :

>>> r = QtCore.QRect(10, 15, 400, 300)


>>> r.getRect(), r.getCoords()
( (10, 15, 400, 300)' (10, 15, 409, 314))
:

isNull ()

- rue, ,

Fa1se-

isVa1id () -

True,

1eft ()

< right ()

< bottom (),

Fa1se-

top () > bottom (),

Fa1se-

top ()

isErnpty () -

True,

1eft () > right ()

norma1ized () ,
bottom (),
>>> r

QRect.

1eft ()

> right ()

top ()

>

QtCore.QRect(QtCore.QPoint(409, 314),
QtCore.QPoint(10, 15))

>>> r
PyQt4.QtCore.QRect(409, 314, -398, -298)
>>> r.norma1ized()
PyQt4.QtCore.QRect(10, 15, 400, 300)

contains (<QPoint> [,

<>]

contains (<>,

<>

[,

<>]

)-

True.

Fa1se-

True,

-.

, .
-

Fa1se.

414

11.

>>> r = QtCore.QRect(O, , 400, 300)


>>> r.contains(O, 10), r.contains(O, 10, True)
(True, False)

contains (<QRect> [, <> J ) -

True,
False- .

rue,
, . .

False. :
>>> r = QtCore.QRect(O, , 400, 300)
>>> r.contains(QtCore.QRect(O, , 20, 5))
True
>>> r.contains(QtCore.QRect(O, , 20, 5), True)
False

intersects (<QRect>) - True,


False ..:....__ ;

intersect (<QRect>)

intersected ( <QRect>) -

. :

>>> r = QtCore.QRect(O, , 20, 20)


>>> r.intersects(QtCore.QRect(10, 10, 20, 20))
True
>>> r.intersect(QtCore.QRect(10, 10, 20, 20))
PyQt4.QtCore.QRect(10, 10, 10, 10)
>>> r.intersected(QtCore.QRect(10, 10, 20, 20))
PyQt4.QtCore.QRect(10, 10, 10, 10)

unite(<QRect>)

united(<QRect>)

- ,

.:

>>> r = QtCore.QRect(O, , 20, 20)


>>> r.unite(QtCore.QRect(301 30, 20, 20))
PyQt4.QtCore.QRect(0, , 50, 50)
>>> r.united(QtCore.QRect(30, 30, 20, 20))
PyQt4.QtCore.QRect(O, , 50, 50)
QRect & &= (), 1
(), in ( <;>), == !=. :

>>> r1, r2 = QtCore.QRect(O, , 20, 20), QtCore.QRect(10, 10, 20, 20)


>>> r1 & r2, r1
r2
(PyQt4.QtCore.QRect(10, 10, 10, 10), PyQt4.QtCore.QRect(O, , 30, 30))
>>> r1 in r2, r1 in QtCore.QRect(O, , 30, 30)
(False, True)
>>> r1 == r2, r1 != r2
(False, True)
1

20.

20.6.

415

. .
QWidget:

showinimized () -

showMaximized () -

showFullScreen () -

showNormal () - , ;
(. . ).

activateWindow () -

Windows,

.
;

setWindowState (<>)

QtCore. Qt :
;

WindowNoState-

WindowMinimized-

Windowaximized- ;

WindowFullScreen- ;

WindowActive- , . . .

n, :

window.setWindowState((window.windowState() &
-(QtCore.Qt.Windowinimized 1 QtCore.Qt.WindowMaximized))
1 QtCore.Qt.WindowFullScreen)
:

isMinimi zed () - True, , False- ;

isMaximi zed () True, ,


False- ;

True, , False-

isFullScreen () -

isActi vewindow () -

rue, , False-

windowstate () -

, .

if window.windowState() & QtCore.Qt.WindowFullScreen:


print ( " ")

20.4.

416
:'"""''''''' ~

................

~. ~

11.

.. ....,.......
~ ~

t...~.~~~~.r. ~~:~~~-~
# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui
c1ass MyWindow(QtGui.QWidget):
def
init (se1f, parent=None):
QtGui.QWidget. init (se1f, parent)
se1f.btnin = QtGui.QPushButton("Cepy")
se1f.btnax = QtGui.QPushButton("Paepy")
se1f .btnFu11 = QtGui .QPushButton (" ")
se1f. btnNorma1 = QtGui .QPushButton (" ")
vbox = QtGui.QVBoxLayout()
vbox.addWidget(se1f.btnin)
vbox.addWidget(se1f.btnax)

def
def
def
def

if

vbox.addWidget(se1f.btnFu11)
vbox.addWidget(se1f.btnNorma1)
se1f.setLayout(vbox)
se1f.connect(se1f.btnin, QtCore.SIGNAL("c1icked()"),
se1f.on min)
se1f.connect(se1f.btnax, QtCore.SIGNAL("c1icked()"),
se1f.on_max)
self .connect (se1f .btnFull, QtCore .SIGNAL ("c1icked () "),
self .on_full)
se1f. connect (se1f .btnNorma1, QtCore .SIGNAL ( "c1icked () ;, ) ,
se1f. on_ norma1)
on_min(se1f):
se1f.showMinimized()
on_max(se1f):
se1f.showMaximized()
on_fu11(se1f):
se1f.showFu11Screen()
on norma1(se1f):
se1f.showNorma1()

n
main
import sys
= QtGui.QApp1ication(sys.argv)
window = MyWindow()

window.setWindowit1e("Paopaae
window.resize(OO,

")

100)

windovJ. show ()
sys.exit(app.exec_())

20.7.

setWindowOpacity ()

:
setWindowOpacity(<Beeceoe

0.0

1.0>)

QWidget.

20.

417

1.0. .

, 1. - .

windowOpacity (),

. 1. . . 5
(

20.5).

[~:~~i.~.~:~.i.~::~~::~~~:i.~~i.~~~~~~::~~~~::::::::,::::::::::::::::::::::::::::,~:::,:::::::::::::::::::::::::::::::::::::::::::::::::~::::::::::::::::::~::::::::::::::::::~::::::::::::::::::::::::::::::::::J
# -*- coding: utf-8 -*from PyQt4 1mport QtGui
import sys
~

window

QtGui.QApplication(sys.argv)
~ QtGui.QWidget()

window.setWindowTitle("oypopaoe ")

window.resize(300, 100)
Wlndow.setWindowOpacityl0.5)
window. show 1)
printlwdow.windowOpacity())

sys.exitlapp.exec

20.8.

#:

0.4980392156862745

1))

,
. ,

. ,

Microsoft Word

, ,
. ,
n.

. ,

setWindowModa1i ty (<>)
QWidget.
QtCore.Qt:

+
+
+

Nonodal- - ;

WindowModal- 1 - ;
Applicationodal-

2 - .

, , . ,

setWindowModality () .
windowodality
,
,

Fa1se-

isModal ().

1). ,

rue,

. ,
. ,
.
(
14.1349

20.6).

418

11.

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys

def show modal_window():


global modalWindow
modalWindow = QtGui.QWidget(windowl, QtCore.Qt.Window)
modalWindow.setWindowTitle("Moaoe

")

moda1Window.resize(200, 50)
modalWindow.setWindowModality(QtCore.Qt.WindowModal)
modalWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)
modalWindow.move(windowl.geometry() .center() modalWindow.rect() .center() - QtCore.QPoint(4, 30))
modalWindow.show()
= QtGui.QApplication(sys.argv)
windowl = QtGui.QWidget()
windowl. setWindowi tle (" ")
windowl.resize(OO, 100)
button = QtGui. QPushButton ( "r ")
QtCore.QObject.connect(button, QtCore.SIGNAL("clicked()"),
show_modal_window)
vbox = QtGui.QVoxLayout()
vbox.addWidget(button)
windowl.setLayout(vbox)
windowl. show ()

window2

QtGui.QWidget()

window2.setWindowitle("o

WindowModal")

window2.resize(500, 100)
window2. show ()
sys.exit(app.exec_())
n n n , ,

( n

i t

). n
n i , .
WdowModal Applicationodal, I.
, t n i n

Window.

i , ,

, . , t n

modalWindow , n n i
. I

n i ,
n

WA_DeleteOnClose setAttribute () i

True.

i i. I i

PyQt

QDialog,

i i

20.

419

. ,
n , ,

QDialog

20.9.

setWindowicon () QWidget.
Qicon (. . 25.3.4).

, .
,
n.
.

supportedimageFonnats ()

QimageReader.

QByteArray. :

from PyQt4 import QtGui


for i in QtGul.QimageReader.supportedimageFormats():
print (str(l, "ascil") .upper(), end=" ")
:

GIF ICO JPEG JPG MNG

PGM PNG

SVG SVGZ TIF TIFF

, ,

setWindowicon ()
Qicon.

QApplication.

.
:

ico = window.style() .standardicon(QtGui.QStyle.SP_MessageBoxCritical)


window.setWindowicon(ico)

QStyle

( :/Python3 2/Li/s ite-packages/PyQt4/doc/htm 11 qsty le.htm 1#Standad Pixmap-enum ).


--r:

PNG

16

16

, n

20.7).

l:~:~~i~:~~:i?:?.~:~i.~~:~~~:~~:~~-~~~~~~:~~::~~~~::::::.:::.:~:.:::.::

. :. : .: : .: : :. : :. : .: : : : : : .: : : : : : : .: .:.: .: : : : . : : . : .

# -'- coding: utf-8 -*from PyQt4 import QtGui


import sys
= QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
window.setWindowitle("Cea

100)
window.setWindowicon(QtGui.Qicon("icon.png"))
app.setWindowicon(QtGui.Qicon("icon.png") ).
window. show ()
sys.exit(app.exec ())

")

window.resize(OO,

#
#

:::.::::::::1

420

20.1 .

11.

( ),

Window ( ackground).

+
+
+

QPalette:

Active Nonnal ~~ ( );
Disaed ~

~ ;

Inactive ~ 2 ~ ( ).

palette ().
- , setColor ()

QPalette. :
stlr([<>,

]<>,

<>)

<> . ,

Window ( Background) . Windowext ( Foreground) ~ .


QPalette.

<> .

QtCore.Qt (, k, white . .) QColor (,

QColor("red"), QColor("#ffOOOO"), QColor(255,

0)

.).

setPalette ()

. , -

. ,
True setAutoFillBackground ().
SS- background-color.
setStyleSheet ().
( ),
( setStyleSheet () QApplication)
( setStyleSheet () QWidget). ,

, ;
. W-,

HTML CSS.

CSS

, ,

. ,

~ . .
. ~ SS- background-color
(

20.8).

20.8. .
# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui
import sys
= QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
window.setWindowitle("eee

")

20.

421

100)
pal = window.palette()
pal.setColor(QtGui.QPalette.Normal, QtGui.QPalette.Window,
QtGui.QColor("#OOBBOO"))
pal.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Window,
QtGui .QColor ("#ffOOOO"))
window.setPalette(pal)
label = QtGui. QLabel (" ")
label.setAlignment(QtCore.Qt.AlignCenter)
label. setStyleSheet ( "background-color: #ffffff; ")
label.setAutoFillBackground(True)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(label)
window.resize(OO,

window.se~Layout(vbox)

window. show ()
sys.exit(app.exec_())
'

20.11.


( ) .

setrush
setBrush([<Cocoe>,

()

]<>,

QPalette.

palette (),

<QBrush>)

setColor (),

.

<>

QBrush.

QBrush(<C

>)

<>= QBrush(<e>[,

<>
<>
<>

<

c>=SolidPattern])

<QPixmap>)
QBrush(<QPixmap>)
= QBrush(<Qimage>)
QBrush(<e>,

<

> QtCore. Qt,


NoBrush, SolidPattern, DenselPattern, Dense2Pattern, DensePattern,
Dense4Pattern, Dense5Pattern, DensePattern, Dense7Pattern, CrossPattern .
{SolidPattern)
(, CrossPattern ).
,

<> .
QtCore.Qt (, k, white . .) QColor (,
QColor("red"), QColot("#ffOOOO"), QColor(255, , 0) .). ,

pal = window.palette()
pal.setBrush(QtGui.QPalette.Normal, QtGui.QPalette.Window,
QtGui.QBrush(QtGui.QColor("#008800"), QtCore.Qt.SolidPattern))
window.setPalette(pal)

422

<QPixmap>

<Qimage>

11.

n n .

n n , ,
.

setPalette 1)

n. n, -n

no

nr n . n,
n

True

setAutofillBackground 1) .

, , n SS

background background-image. SS- background-repeat

n n . n

repeat, repeat-x (n no ), repeat-y (n no


no-repeat ( n).

n. ( n

n),

background-image)

SS-

20.9).

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys
= QtGui.QApplicationlsys.argv)
window = QtGui.QWidgetl)
window.setWindowitlei"opaee

")

100)
pal = window.palette()
pal.setBrush(QtGui.QPalette.Normal, QtGui.QPalette.Window,
QtGui. QBrush (QtGui. QP ixmap ( "imgl. png") ) )
window.setPalettelpal)
label = QtGui. QLabel (" ")
label.setAlignment(QtCore.Qt.AlignCenter)
label.setAutoFillBackground(True)
vbox = QtGui.QVBoxLayout()
vbox.addWidgetllabel)
window.setLayoutlvbox)
window. show 1)
sys.exitlapp.exec_l))
window.resizeiOO,

20.12.

, n :

\.

nr , n,

2.

PNG.

QPixmap, n

r n .

3.

n n.

20.

423

4.

5.

setask

()

mask ()

QPixrnap.

. , , u :

QtCore.Qt.Window

QtCore.Qt.framelessWindowHint

QPixrnap

QLabel,
setPixrnap (),

setMask ().

,
. u (

f h:t.20.:t' .. ~11'J. ~ n~~~ ~l

..................,..... ...........;................... ...........................;,;,................. ;.................;;,;.................. .....


~

~:

;.,,;,~;;,

...;;;...

,;~.;

20.1 0).

....;.......:

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys
= QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
window.setWindowflags(QtCore.Qt.Window 1 QtCore.Qt.framelessWindowHint)
window.setWindowTitle (" ")
window.resize(300, 300)
pixrnap = QtGui. QPixrnap ( "fon. png")
pal = window.palette()
pal.setBrush(QtGui.QPalette.Normal, QtGui.QPalette.Window,
QtGul.QBrush(pixrnap))
pal.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window,
QtGui.QBrush(pixmap))
window.setPalette(pal)
window.setMask(pixmap.mask())
button = QtGui.QPushButton("ap ", window)
button.setfixedSize(lSO, 30)
button.move(75, 135)
QtCore.QObject.connect(button, QtCore.SIGNAL("clicked()"),
QtGui. qApp, QtCore. SLOT ( "qui t () ") )
window. show ()
sys.exit(app.exec ())

20.1 3.


. ,
. ,

.
.
.

PyQt

. u .

424

11.

QWidget:

setToolTip(<Tec>l-

HTML.

, ;

+
+

tool Tip ( 1 -

setWhatsThis (<> 1 -

, .
,

<Shift>+<FI>.

n.

.
, .

HTML.

~1 , t ;

whatsThis ( 1 -

..

20.11 ).

[ 2D.'fi; 13J1is ni(t,

: :.:.: ::.=:; ::=.: .= : ....;,;;;,;;,,,;,,,;,,,:;;.;,=,;;;, ...... :.:.: : .. ;,,;,;,,;,;,=,;,,;;,;:;~ i:.:::::::. :: ... ;,;;,,;;........ ;;;,,,,,;... :.......

=. ,

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys
= QtGui.QApplication(sys.argvl
window = QtGui.QWidget(flags=QtCore.Qt.Dialogl

window.setWindowitle("Bcae ")

window.resize(300, 70)
button = QtGui. QPushButton ( "r ", window)
button.setFixedSize(l50, 30)
button.move(75, 20)
button.setToolTip (" ")
window.setToolTip("o

button.setWhatsThis("o

window.setWhatsThis("o

")

")

")

QtCore.SIGNAL("clicked()"l,
QtGui. qApp, QtCore. SLOT ( "quit () ") )

QtCore.QObject.conect(button,

show ()
sys.exit(app.exec_())

widow.

20.14.

1 quit ( 1
exit ( [returCode=O] 1 .
, .
.

True,

close ( 1 QWidget.
False- .
closeAllWidows ( 1 QAppllcatlo.

20.

WA_DeleteOnClose

425

QtCore.Qt

. .
, .

setAttribute ():

window.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)

close ()
QEvent .Close.
closeEvent (), .
QCloseEvent, accept () (
) ignore () ( ). ;

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys
= QtGui.QApplication(sys.argv)
window = QtGui.QWidget(flags=QtCore.Qt.Dialog)
w1ndow. setWindowi tle (" ")
window.resize(OO, 70)
button = QtGui.QPushButton("ap ", window)
button.setFixedSize(l50, 30)
button.move(75, 20)
QtCore.QObject.connect(button, QtCore.SIGNAL("clicked()"),
window, QtCore.SLOT("close()"))
window. show ()
sys.exit(app.exec ())

20.12).

21

.
. -
, -

.
, , ,
, .
, .

21.1.

- ,
, .

nnt(<>,

connect ()

<>,

QObject.

<ConnectionType>])
<ConnectionType>])
<>[, <ConnectionType>])

<>[,

nnt(<l>,

~>,

<2>,

<>[,

nnt(<l>,

<>,

<2>,

, ( )
<2>.nnt(<l>,

<>,

<>[,

connect ():

<ConnectionType>])

l <>,
<>. ,

True.

. <>
.
QtCore.SIGNAL("<Haae

SIGNAL ().

>( [n

:
n])

")

, ,

clicked (bool=O).

, . ,
. ~ :

QtCore.SIGNAL("clicked() ")
.
:

QtCore.SIGNAL("clicked(bool) ")

427

21.

(False),

. .

clicked ().

<> :

+ ;
+ ;
+ .
call

().

21.1.

[
.. 21.1. FJ~i ~~ ~911;.9J:~~J"'~~9<>9~()
.:. . ...... .. :...... ......... .... "; .. ............ :..:.'.. ............ ...........::. :............. . ..:: ..:. :.. .....:......:.
.......... ,; . :;.:. .. .. .. .. .:: ......... ...................................... :.... ........ .. ..... ....
~.'"

~:'.:

'

'." .~

:~.

"'

,:,, ,;, ,,,, ,;~

;;, ~.: ~;

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys
def on_clicked():
print ("

on_clicked () ")

class MyClass():
def
init (self, =):
self.x =
def
call (self) :
rint("

MyClass.

call

()")

MyClass.on_clicked()")

print("x =", self.x)


def on_clicked(self):
rint("

obj = MyClass ()
= QtGui.QApplication(sys.argv)
button = QtGui.QPushButton("Ha ")
#
QtCore.QObject.connect(button, QtCore.SIGNAL("clicked()"), on clicked)
#
QtCore.QObject.connect(button, QtCore.SIGNAL("clicked()"),
obj.on_clicked)
#
QtCore .QObject. connect (button, QtCore. SIGNAL ( "clicked () "), MyClass (10))
QtCore.QObject. connect (button, QtCore. SIGNAL ( "clicked () "), MyClass (5))
button. show ()
sys.exit(app.exec_())
:

on_clicked()
MyClass.on_clicked()
MyClass. call ()

MyClass.

= 10

=5

call

()

'

';'

'.'

"

428

connect 1)

11.

Qt-

<2>. n 11 ,


.(

Qt.
21.2).

n n n n11

! \1 21.2; ~w 1 nd~n~\ n

O:.... o,,,.,,,,..,,,.,.,.,,...; ..~;,;-.;,.,;:_.,,,,y.,,~,;,,..,,,..,;,.,.,,,;,,;,;,,.;,.,,,,,.,;,,.,,,.,,;,.,,.,;o;;,;.,,v,,,,~,,;;.,;,~,;,,,,,;,-.,;.,,,,;,.,;;;,.,;;,;,,,,,,,.,,,;,..,,,.,,,,,,.,,..,,,..,,.,,.,,,.,,,.,,,.,,.,,,,,,.,,,.,

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys

,,
= QtGui.QApplication(sys.argv)
button = QtGui .QPushButton (" ")
QtCore.QObject.connect(button, QtCore.SIGNAL("clickedl)"),
,
QtCore. SLOT 1"quit 1) "))
button. show 1)
sys.exit(app.exec_l))

113

n , n

, n

Pytho11

SLOT 1)

connect 1)

n11

n ~

qui t 1)

QtCore. QObj ect. connect lbutton, QtCore. SIGNAL 1"clicked () ") ,


CJUi t i

connect 1) n n ~1 .

n n (

21.3).

..... . . ........ ........... .............. ........................... ... ... ............ ....... .. .............. ............................... ... ... .... .................................... .............. ....................................................
~;,;;.~i-':iJ~~~;:n~-~~~:.~:.:,~~t~~:~..~:~.:
~~)g:.::>::;:: ":/
_,
:
........................... :.;;... ;.:::... :.... :.... ;.. :.....:;.: ...=
......... ;;,; . :~.. ,;;,=~.; ..;;,; .............~;;........ ;......... ;,;;,,,,-;;i,:::... : ....... ;.:; ....... : ........;;; ................. :.= ......................................................................:............. J
,.

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui

class MyWindow(QtGui.QWidget):
def
init (self, parent=None):
QtGui.QWidget. init (self, parent)
self.buttonl = QtGui.QPushButton("oa l.
self .button2 = QtGui .QPushButton (" 2")
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.buttonl)

")

vbox.addWidget(self.butto2)

self.setLayout(vbox)
self.resize(OO, 100)
# l 2
self.connect(self.buttonl, QtCore.SIGNAL("clicked()"),
self.button2, QtCore.SIGNAL('clicked() '))
# n l 14 )
self.connect(self.button2, QtCore.SIGNAL("clicked()"),
self, QtCore.SLOT("on_clicked_button2()"))

21.

429

# 2 (3 )
self.connect(self.button2, QtCore.SIGNAL("clicked()"),
QtCore.SLOT("on_clicked_button2()"))
@QtCore.pyqtSlot()
def on_clicked_button2(self):
print (" 2")

if

n
main
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

_init_()

MyWindow,

QWidget.

addWidget ().

setLayout ()

. .
,

connect () .
QObject,
connect () . on_ clicked_
button2 (), @QtCore .pyqtSlot () .
, Qt-

~,
. ,

connect (),

self.connect(self.buttonl, QtCore.SIGNAL("clicked()"),
self.button2, QtCore.SIGNAL('clicked() '))
.

connect ( ) :

self.connect(self.button2, QtCore.SIGNAL("clicked()"),
self, QtCore.SLOT("on_clicked_button2()"))
connect ():

self .connect (self .button2, QtCore. SIGNAL ( "clicked () "),


QtCore.SLOT("on_clicked_button2()"))

<ConnectionType>

.
, . . GUI- .

AutoConnection-

- .

QtCore.Qt:

DirectConnection,

QueuedConnection;

DirectConnection- 1 - .
;

430

11.

QueuedConnection- 2 - .
;

BlockingQueuedConnection- 4 - 'I QueuedConnection,

, . ,
;

UniqueConnection- - AutoConnection,
. ,

button2

, :

st

self.connect (self.button2, QtCore.SIGNAL("clicked() "),


self, QtCore.SLOT("on_clicked_button2()"),
QtCore.Qt.UniqueConnection)
print(st)
st = self .connect (self .button2, QtCore.SIGNAL("clicked() "),
self, QtCore.SLOT("on_clicked_button2()"),
QtCore.Qt.UniqueConnection)
print(st)
=

True
False

Autocornpatconnection- 3 - Qt 3.

21.2.

QObject:

ockSignals (<>) - ,

rue, , False.
;

signalsBlocked () - True, ,
False- ;

disconnect () - .
. :
disconnect(<Oe>,
disconnect(<Oel>,

<>,
<>,

<>)
<2>,

<>)

disconnect () <> 11.


<> .

, .
, disconnect () True. , 11
. disconnect (), , ~1

. , :

self. connect (self .buttonl, QtCore. SIGNAL ( "clicked () "),


self, QtCore. SLOT ( "on_clicked_buttonl () "))

21.

431

self. connect (self. buttonl, QtCore. SIGNAL ( "clicked () ") ,


QtCore.SLOT("on_clicked_buttonl()"))
:

self.disconnect(self.buttonl, QtCore.SIGNAL("clicked()"),
selC QtCore. SLOT ( "on_clicked_buttonl () "))
n . n n

connect

(). n n

n.

QObject.
disconnect ()

n n

n n .
, n n

n.
n (

21.4).

n 1

clicked (). n,

. n ,
,. n
.

~~~~~;21:4~ ~~~~~;~ ~ ;~~~~~~~~~;~~~~::


;;, ,,, . . ,, " . " .. ' " " .;. . . 1" ;. ;,..;;, . . " . " . . .

. . . . . . . . .

~: ;;;:~.; . . ~.';. . . .;. . ::. . . . .: ; ; , " ;,; ~ ;;; ; ;~;:,, : . . : : . :. " ~; .. ,; . . ; :~;, ,',, . . . ;;, i~.~.;; ~--...:,, ...... ". ,,... ,............................ ;................. "'" ........ 1 . . . . . . . . ' 1 " \ ... ' . . . " ' . ' . . . . . . . . . . "

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyWindow(QtGui.QWidget):
def
init (self, parent=None):
QtGui.QWidget. init (self, parent)
self .setWindowTitle (" ")
self.resize(OO, 150)
self.buttonl
QtGui. QPushButton ( " ")
se lf. but ton2
QtGui .QPushButton ("")
self.button3
QtGui.QPushButton("Paopoa")
self. button4
QtGui. QPushButton (" ")
self.button.setEnaed(False)

vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.buttonl)
vbox.addWidget(self.button2)
vbox.addWidget(self.button)

vbox.addWidget(self.button4)
self.setLayout(vbox)
self.connect(self.buttonl, QtCore.SIGNAL("clicked()"),
QtCore.SLOT("on_clicked_buttonl()"))
self.connect(self.button2, QtCore.SIGNAL("clicked()"),
QtCore.SLOT("on_clicked_button2()"))
self.connect(self.button3, QtCore.SIGNAL("clicked()"),
QtCore.SLOT("on_clicked_button3()"))
self.connect(self.button4, QtCore.SIGNAL("clicked()"),
QtCore.SLOT("on_clicked_button4()"))

......... ' ......... '.";

432

11.

@QtCore.pyqtSlot()
def on_clicked_buttonl(self):
print (" buttonl")
@QtCore.py~Slot()

def on_clicked_button2(self):
self.buttonl.ockSignals(True)
self.button2.setEnaed(False)
self.button.setEnaed(True)

@QtCore.pyqtSlot()
def on_clicked_button(self):
self.buttonl.ockSignals(False)

self.button2.setEnaed(True)
self.button.setEnaed(False)

@QtCore.pyqtSlot()
def on_clicked_button4(self):
self.disconnect(self.buttonl,
QtCore. SIGNAL ( "clicked () "), self,
QtCore.SLOT("on_clicked_buttonl() "))
self.button2.setEnaled(False)
self.button.setEnaed(False)
self.button4.setEnaed(False)

if

"

ma:i,n

import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())
,

"

buttonl ".

.
. n ~1.

.
, ,
.
,

QWidget:

stnd(<>)-

False,

. ,

True;

setDisaed (<>)

True,

. ,

False.
, , isEnaed

True,

False-

().

21.

21.3.

433

n. n11, n n11
n

<Enter>

n . n n
n

emit ()

<>.mit(<>[,

<

QObject.

>])

n <> n

SIGNAL ().

QtCore. S IGNAL ("<

>

( [

) ")

n n n

n. , n .
n n (

21.5). n
clicked () ( n).

n n .
, , n n.
.

1i~~~~~; :z1:i~~~~-~;'~~;~~'~:i ~;~~i~J;.;,


~

. . . ,. . ,. . .". . ". . . . . . . . . . . . . . . . .,. ,. . . . . , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .:

.......................................... :..........~ ......~ ....; :........ ~ ~.... ~.;: ;........ : ; : ;.;,,; ....... ; .;.:.....~.= ..... :......~ ;:.:::.::~ ;;.~ ...:;:;,,;~:;.:~;.;,:.:;,;;,.~.:.; :;,,;,,;,,:. ;:-...........~ ..........................................:

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyWindow(QtGui.QWidget):
def
init
(self, parent=None):
QtGui.QWidget. init (self, parent)
se1f. setWindoWi t1e (" ")
se1f.resize(300, 100)
self.button1 = QtGui.QPushButton("Ha ")
self.button2 = QtGui.QPushButton("oa 2")
vbox = QtGui.QVBoxLayout()
vbox.addWidget(se1f.button1)
vbox.addWidget(self.button2)
se1f.setLayout(vbox)
self. connect ( se1f. button1, QtCore. SIGNAL ( "c1icked () ") ,
se1f.on_c1icked_button1)
self. connect ( se1f .button2, QtCore. SIGNAL ( "c1icked () ") ,
se1f.on_c1icked_button2)
se1f.connect(se1f.button2, QtCore.SIGNAL("mysigna1"),
se1f.on_mysigna1)
def on_c1icked_button1(se1f):
print (" buttonl")
#
self.button2.emit(QtCore.SIGNAL("c1icked(boo1)"), Fa1se)
se1f.button2.emit(QtCore.SIGNAL("mysigna1"), 10, 20)
def on_c1icked_button2(se1f):
print (" button2")

434
def on_mysignal(self,

):

rint("

print("x =",
if

11.

"=",

mysignal()")

n
==." main "
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

buttonl
button2

= 10

mysignal()

= 20

, '
. ,
.


. :

self .button2 .emit (QtCore.SIGNAL("mysignal"), 10, 20)


.
:

self.connect(self.button2, QtCore.SIGNAL("mysignal(int, int)"),


self.on_mysignal)
:

self .button2 .emit (QtCore. SIGNAL ( "mysignal (int, int) "), 10, . 20)

PyQt_PyObject.

. ..,
:

self. connect (self .button2, QtCore. SIGNAL ( "mysignal (PyQt_PyObject) "),


self.on_mysignal)
:

self .button2 .emit (QtCore.SIGNAL("mysignal (PyQt_PyObject) "), 20)


self .button2 .emit (QtCore. SIGNAL ( "mysignal (PyQt_PyObject) "), [1, "2"])

emit ().

, . ,

click ().

, :

self.button2.emit(QtCore.SIGNAL("clicked(bool)"), False)
:

self.button2.click()

21.

435

n n n
.

21.4.

PyQt

n ,

. ,. n

connect ():
<n>.<>.nn~t(<>[,

type=<ConnectionType>])

<n>.<>[<>].nnt(<>[,

type=<ConnectionType>])
n <> n,
<>. .
n n,
n .. n <> n
, n

. n

type

type

n n

AutoConnection.

self.buttonl.clicked.conne~t(self.on_clicked_buttonl)

self.button2.clicked["bool"] .connect(selfoon_clicked_button2)
n

disconnect ():

<n>.<>disnnt([<>])
<n>.<>[<>] .disnnt([<>])

n <> , , ,
n . :

selfobuttonl.clickedodisconnect()
selfobutton2.clicked["bool"] odisconnect(selfoon_clicked_button2)
n

emi t ():

<n>.<>mit([<>])
<n> <> [<>]

; emi t ( [<>] )

self.button2oclickedoemit(False)
self.button2oclicked["bool"] oemit(False)
n n

pyqtSignal ()

QtCore. :
< >=

int,

pyqtSignal(*types[,

n])

types n n Python, n bool

n :

mysignal = QtCoreopyqtSignal(int, name="mysignal")


n ++ :

mysignal = QtCore pyqtSigna1 ( "QString", name="mysignal")

436

n n, n

n .

11.

types

. , n n

mysignal = QtCore.pyqtSignal ( [int], [str],

int 11 str:

nae="mysignal")

n n n .
n . n n ,
n . .

n n n.

21.6).

n (

n n n.

..... ............................. ....................... ,..........,..,......................... ...,.......................,......... ...................................................... ...................................................................................


: r 21.6. 4i . ..t
~

,~

;. ;'. ~ ' : ; : :.. '; :=.; :} ,,; :. :. i.; .... :; ... ;.............. :......,:, :;; ... ;:. ::......:... :... ,;; ........ ;... :........... ;,.., ... ............ ....... '.. .. ................... . ................ ' .... ' ' ....... .. i

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyWindow(QtGui.QWidget):
mysignal = QtCore .pyqtSignal ( [int], [str],
def
init (self, parent=None):
QtGui.QWidget. init (self, parent)
self.setWindowitle("Opaoa

self.resize(OO,

nae="mysignal")

")

100)

self.buttonl
QtGui.QPushButton("Ha ")
self.button2 = QtGui.QPushButton("oa 2")
self.button = QtGui.QPushButton("Ya ")
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.buttonl)
vbox.addWidget(self.button2)
vbox.addWidget(self.button)

self.setLayout(vbox)
#
self.buttonl.clicked.connect(self.on_clicked buttonl)
self.button2.clicked["bool"] .connect(self.on_clicked_button2)
self.button3.clicked.connect(self.on_clicked_button3)
self.mysignal[int] .connect(self.on_mysignal)
self.mysignal[str] .connect(self.on_mysignal)
def on_clicked_buttonl(self, status):
print("Haaa n buttonl", status)
#
self. button2. clicked [ "bool"] . emi t ( E'alse)
self.mysignal[int] .emit(lO)
self.mysi~nal[str] .emit("cpoa")

def on_clicked_button2(self, status):


print("Haaa n button2", status)
def on_clicked_button(self):
print (" n button")
#
self.buttonl.clicked.disconnect()

21.

437

self.button2.clicked["bool"] .disconnect(
self.on clicked_button2)
self.mysignal[int] .disconnect()
self.mysignal[str] .disconnect()
self.button.setEnaled(False)

def on_mysignal(self, n):


rint("

if

\n

n -"

n)

main
name
import sys
= QtGul.QApplicacion(sys.argv)
window = MyWindow()
wlndow. show 1)
sys.exitlapp.exec_l))

n, , n

@pyqtSlot 1).

, ,

QObJect.

QObject

@QtCore.pyqtSlot(*types, name=None, result=None)


n types 1n 1n tl, n bool
int, n . n ++
. n n, n

types

. n n n .
n . n

name ,

. n result n
n , . n ,
. n ,

n n . n

@pyqtSlot 1) n 21.7.

~.~~~.~.~ ~~.::..~ ~.:.~~~~~~.~~.~~.~~.~~~:~~~.~~ ~.~~.~:~5. ~.>........................................................................................................................,

1...

..

..

..

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import sys
class MyClass(QtCore.QObject):
def
init lself):
QtCore.QObject. init
@QtCore.pyqtSlot()
def on_clickedlself):

(self)

print("ona . on_clicked()")
@QtCore.pyqtSlot(bool, name="myslot")
def on_clicked21self, status):
rint(" . myslot(bool)", status)

obj

MyClass ()
QtGui.QApplication(sys.argv)

438

11.

button = QtGui .QPushButton ( " ")


QtCore .QObject. connect (button, QtCore .SIGNAL ( "clicked () "),
obj, QtCore.SLOT_("on_clicked() "))
QtCore.QObject.connect(button, QtCore.SIGNAL("clicked(bool)"),
obj, QtCore. SLOT ( "myslot (bool) ") )
button. show ()
sys. exit (. _ () )

21.5.

connect () .

- ,
,
. :

lmd-, .

10:
QtCore.SIGNAL("clicked()"),
: self.on_clicked_button1(10))

self.connect(s~lf.button1,
lamda

,
lmd-,
lmd- , . :
=

10

self .connect (self .button1, QtCore.SIGNAL ( "clicked () "),


lamda =: self.on_clicked_button1(x))

call

().

. :

class MyClass():
def __init __ (self, =):
self.x =
def
call (self) :
print("x =", self.x)
:

self.connect(self.buttonl, QtCore.SIGNAL("clicked()"),
MyC1ass (10))

partial ()

functools.

from functools import partial


partial(func[, *args] [, **keywords])
:

self.connect(self,button1, QtCore.SIGNAL("clicked()"),
partial(self.on_clicked_button1, 10))
,

clicked(bool)

439

21.

self. connect (sel f .but tonl, QtCore. SIGNAL ( "clicked (bool) ") ,
partial(self.on_clicked_buttonl, 10))
:

def on_clicked_button1(self, , status):


print("Haaa n button1", , status)
:

button1 10 False

21.6.

11

<Id> =

QObject.

tirnerEvent

().

startTirner ()

<>.strtimr(<>)

startTirner () ,

. <> , l.:

tirnerEvent (). tlrnerEvent ():

tirnerEvent(self,

<

QTirnerEvent>)

tirnerEvent ()
tirnerid () QTirnerEvent. :

<Id>

=<

QTirnerEvent>.tirnerid()

. <
> ,
.
,

QObject.

~t

killTlrner () 11

<Oe>.killTirner(<Id>)

11,

startTirner ().

,
,

21.8).

21.8.

Q .~:.10 .

...............................................................................::......... :.............:... ; ................................................. :.::....:................:.;...................

# -*- coding: ucf-8 -*frorn PyQt4 irnport QtCore, QtGui


irnport tirne
class MyWindow(QtGui.QWidget):
def
init (self, parent=None):
QtGui.QWidget. init (self, parent)
self.setWindowTit1e("ac

self.resize(200, 100)

")

440

11.

self.timer id =
self.label = QtGui.QLabel("")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.buttonl = QtGui.QPushButton("anyc")
self.button2 = QtGui.QPushButton("Ocao")
self.button2.setEnaed(False)

vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.label)
vbox.addWidget(self.buttonl)
vbox.addWidget(self.button2)
self.setLayout(vbox)
self.connect(self.buttonl, QtCore.SIGNAL("clicked()"),
self.on_clicked_buttonl)
self.connect(self.button2, QtCore.SIGNAL("clicked()"),
self.on_clicked_button2)
def on_clicked_buttonl(self):
self.timer_id = self.startTimer(lOOO) # 1
self .buttonl. set.Enaed ( False)
self.button2.setEnaed(True)

def on_clicked_button2(self):
if self.timer id:
self.killTimer(self.timer_id)
self.timer id =
self.buttonl.setEnaed(True)
self.button2.setEnaled(False)

def timerEvent(self, event):


self.label.setText(time.strftime("%H:%M:%S"))
if

n
main
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

startTimer () killTimer ()
Qtcore. :

QTimer

<>= Qimer({parent=None])

setinterval

(<>) - ,

timeout ().

. <> ,
;

start ( [<> J ) -

. ,
,

stop ()

interval () ;

- ~;

21.

441

setSing1eShot (<>) - True, , - ;

+
+
+

interva1 ()

- ;

timerid () - -1;
isSing1eShot () True,
Fa1se- ;

isActive () -

True,

Fa1se-

1 QTimer scartTimer ()

killTimer()

(21.9) .

............,.........................................,....,.......................,., ..........................................................................................................................

! 21.9. nn11 n~ Qri/1\e;r:


;.; ... : "

' ' ' ' ' , , . . . . ' ' . ' "

"

1 ' ' " . ' . ' ' : . ' : ' 1 . . . . . . . . . . . . . : , ; ' " ; . . . . . . : : . . . . : .....

. . . .
~-. '

" : : . ;: 1 "

. . . . . . . . . . . . . ' , ; ' 1

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


import time
c1ass MyWindow(QtGui.QWidget):
def
init (se1f, parent=None):
QtGui.QWidget. init (se1f, parent)
se1f. setWindowi t1e ("n QTimer")
se1f.resize(200, 100)
se1f.1abe1 = QtGui.QLabe1("")
se1f.1abe1.setA1ignment(QtCore.Qt.A1ignCenter)
self .button1 = QtGui .QPushButton ("n")
self .button2 = QtGui .QPushButton ("")
se1f.button2.setEnaled(False)

vbox = QtGui.QVBoxLayout()
vbox.addWidget(se1f.1abe1)
vbox.addWidget(se1f.button1)
vbox.addWidget(se1f.button2)
se1f.setLayout(vbox)
se1f.connect(se1f.button1, QtCore.SIGNAL("c1icked()"),
se1f.on_c1icked_button1)
se1f.connect(se1f.button2, QtCore.SIGNAL("c1icked()"),
se1f.on_c1icked_button2)
se1f.timer = QtCore.QTimer()
se1f.connect(se1f.timer, QtCore.SIGNAL("timeout()"),
se1f.on_timeout);
def on_c1icked_button1(se1f):
se1f.timer.start(1000) # 1
se1f.button1.setEnaled(Fa1se)
se1f.button2.setEnaled(True)

def on_c1icked_button2(se1f):
se1f.timer.stop()
se1f.buttonl.setEnaled(True)
se1f.button2.setEnaled(Fa1se)

442

11.

def on_timeout(self):
self .label. setText (t ime. strftime ("%; %: %S") )
if

rnain "
name
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

QTimer

singleShot ( 1,

,
. . :
QtCore.QTimer.singleShot(<epa>,

<>)

QtCore.QTimer.singleShot(<epa>,

<>,

<>)

singleShot ( 1:

QtCore.QTimer.singleShot(lOOO, self.on_timeout)
QtCore.QTimer.singleShot(lOOO, QtGui.qApp, QtCore.SLO("quit()"))

21.7.

. ,
, . ,
, ,
,

keyPressEvent ( 1.

, ,
.

QEvent

accept ( 1 -

, ,

closeEvent ( 1 accept ( 1

, .
;

+
+

ignore ( 1 - , , closeEvent ( 1
ignore ( 1 , ;
setAccepted (<> 1 -

rue,

+
+

isAccepted ( 1 -

accept ( 1), False- (

ignore ( 1);

registerEventType ( [<> J 1 -

. .

QEvent. user (1000) QEvent .axuser

( 65535). ;

spontaneous ( 1 -

True, , False,

21.

443

type () - . (
QEvent):

- ;

1 - Timer- ;

2 - MouseButtonPress-

3 - MouseButtonRe1ease-

4 - MouseButtonDC1ick- ;

5 - Mouseove-

7 - KeyRe1ease-

8 - Focusin- ;

9 - FocusOut- ;

KeyPress -

;
;

Enter- ;

10 -

11- Leave- ;

12- Paint-

13- Move-

14- Resize-

17 -

18- Hide-

19- C1ose-

24- WindowActi vate-

25- WindowDeacti vate-

26- ShowoParent- ;

27 -

31- Whee1-

40- C1ipboard- ;

;
;

Show- ;
;
;

HideToParent

- ;

60- DragEnter-
;

61 -

DragMove-

62 -

DragLeave- -

63 -

Drop-

68- ChildAdded- ;

69- Chi1dPo1ished- ;

71- Chi1dRemoved- ;

74- Po1ishRequest-

75- Po1ish- ;

444

11.

ContextMenu- ;

82 -

99- ActivationChange-

103- WindowB1ocked- ;

104- WindowUnlocked- n 1 ~

105- WindowStateChange-

121- App1icationActivate-

122- App1icationDeactivate-

1000- user- n ;

65535- axuser- n .

;
n n n;
n n;

n nn

event (self,

<event>). n <event> n n11

. n iI, n,

MouseButtonPress n

QMouseEvent,

11

KeyPress- n QKeyEvent. ,
.

event () True, n, Fa1se-

n . True, n n
. n n ,

event

r) n . :

return QtGui.QWidget.event(se1f,

QWidget n

event (). 1;1 1 , ,

. n, n QLabe1 :

return QtGui.QLabe1.event(se1f,

n , 11I

21.10.

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyWindow(QtGui.QWidget):
def

init

(self, parent=None):

QtGui.QWidget.

init

(self, parent)

se1f.resize(300, 100)
def event(se1f,

):

if e.type() == QtCore.QEvent.KeyPress:
print

("

")

e.key(), ",:", e.text())


elif e.type() == QtCore.QEvent.Close:
print (" ")
print("Ko:",

445

21.

elif e.type() == QtCore.QEvent.MouseButtonPress:


r1nt(" !l.

'JJr:",

re<.ur QtGu1.QW1dget.evet(self,

if

)#

.(),

.())

m1

import sys

= QtGui.QApplication(sys.argv)

widow

= MyWindow()

window. show ()
sys.exit(app.exec ())

21.8.

13

n , n n ,

, , nn closeEvent ().

nn ,
.

21.8.1.

(, ,
) n :

changeEvent (self,

<event>) - n , n

n. , n
,

n,

, , . (n n ).

WindowStateChange

<event>

QWindowStateChangeEvent. oldState (),


n n ;

<event>

<event>) - n n. n

showEvent (self,

n n

<event>)- n n. n

hideEvent (self,
<event>

QShowEvent;

n n

QHideEvent.

n ,
, (
:""'''"'<'"' ''>~"' "'" " < "'<">"'~""

21.11 ).

"" "' '."" " ..... """'" "., " " "'"!.'~" >~""'" " """" """"

i:...........
21.1.1. k
::............ :....... ::; .. .... :.......:...... ..... :.:: ........ :..... :................. ::::............. ......:"'": ........
,

:~.:

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyWindow(QtGui.QWidget):
def
in1t
(self, parent=None):
QtGui.QWidget.
self.resize(OO,

init

100)

(self, parent)

:~..........

"" " "''" <<"''" " ""'" "' '.'

.,

.................................................................

446

11.

def changeEvent(self, ):
if e.type() == .QtCore.QEvent.WindowStateChange:
if self.isMinimized():
print (" ")
elif self.isMaximized():
print (" ")
elif self.is~ullScreen():
print ( " ")
elif self.isActiveWindow():
print (" ")
QtGui.QWidget.changeEvent(self, ) #
def showEvent(self, ):
print (" ")
#
QtGui.QWidget.showEvent(self, )
def hideEvent(self, ):
print (" ")
QtGui.QWidget.hideEvent(self, )
#
if

main

"

import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

21.8.2.

moveEvent (self, <event>)- .


<event> QMoveEvent.
QMoveEvent:

pos 1)

oldPos 1)

QPoint

fl;

QPoint

reslZeEvent (self, <event>)- .


<event> QResizeEvent.
QResizeEvent:

size 1)

oldSize 1)

QSize

- n

QSize

n J.

. [ r 2112. .t.t l'l'

....................... ............................ ... .

i ............... ; ................ ;; ..................: ....................... ;;,.,;........................................................; ............................ ; ................................................................ .

# -*- coding: utf-8 -*from PyQt4 import QtGui


class MyWindow(QtGui.QWidget):
def
init (self, parent=None):

21.12 .

...............

447

21.

QtGui.QWidget.
self.resize(OO,

init (self, parent)


100)

def moveEvent(self, ):
print("x = {0}; = {l}".format(e.pos().x(), e.pos().y()))
QtGui.QWidget.moveEvent(self, )
#
def resizeEvent(self, ):
print("w = {0}; h = (l}".format(e.size() .width(),
e.size() .height()))
QtGui.QWidget.resizeEvent(self, ) #
if

n
main
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

21.8.3.

( ) ,

paintEvent (self,
<event>). <event>
QPaintEvent, :

rect () -

QRect

, ;

region () - QRegion , .

, , ,
.

,
. , ,
.

, , -

repaint () -

QWidget:

paintEvent ()

, ,
setUpdatesEnaed

().

repaint ()
repaint(<X>,

<>,

<>,

<>)

repaint(<QRect>)
repaint(<QRegion>)

update () -

, ..
.

, .

448

repaint ().

update ()
update(<X>, <>,
update(<QRect>)
update(<QRegion>)

21.8.4.

update ()

/1.

<>,

<>)

closeEvent (self, <event>).


QCloseEvent.

, -

<event>

close ()

ignore ()

accept ().

Yes,

No

21.13).

, .

:''''''."'''''~

.. ~:~:.::.:.:.:.::~:~..::::..t::!".''''~''''.'.''::.<.::"'''''''~:.::::::":"'''''"'''': ................... , ................................. ..

[.:.~:~~~-~-~--~~.:~.~.: . 9:~.~~~~~. ~~-~f.~~-~~~~. ;. . ,;. ;,";:. . . ,.:, . ,.:.:. :. :;. . ;.l..: ............................................................................................................!
# -*- coding: utf-8 -*from PyQt4 import QtGui
class MyWindow(QtGui.QWidget):
def
lnit (self, parent=None):
QtGui.QWidget. init (self, parent)
self.resize(OO, 100)
def closeEvent(self, ):
result = QtGui.QMessageBox.question(self,
"

"

QtGui.QMessageBox.Yes
QtGui.QMessageBox.No)
if result == QtGui.QMessageBox.Yes:
e.accept ()
QtGui.QWidget.closeEvent(self, )
else:
. ignore ()
if

n
main
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

",

?",

QtGui.QMessageBox.No,

21.

449

21.9.

. ,

<Enter>

<FI>

. .

21.9.1.

( )

. 'I QWidget:

setFocus ( [<> J )

, -

. <> .

+
+
+

QtCore .Qt:

MouseFocusReason- - ;

TabFocusReason- 1-:- <>;

BacktabFocusReason- 2 - <Shift>+<Tab>;

ActiveWindowFocus.Reason- 3 ~ ;

PopupFocusReason- 4

ShortcutFocusReason- 5 - ;

MenuBarFocusReason- - - ;

OtherFocusReason- 7 -

- ;

clearFocus () - ;
hasFocus () - True, ,
False- ;
focusWidget ()

setFocus (). .

, . , ;

setFocusProxy(<QWidget>)- ,
;

focusProxy () -

. , None;

focusNextChild () -

. <>. rue,

, False- ;

fc:cusPr.eviousChild () -

, .

<Shift>+<Tab>.

True, , False- ;

focusNextPrevChild(<a>)- True,

focusNextChild (). False,


focusPreviousChild (). rue,
, False- ;

15

1349

450

11.

setTabOrder (<1>, <2>) - n


n <>. .
<2> ,
<1>. n , .

widget1 -> widget2 -> widget -> widget4:

QtGui.QWidget.setTabOrder(widget1, widget2)
QtGui.QWidget.setTaOrder(widget2, widget3)
QtGui.QWidget.setTabOrder(widget, widget4)

setFocusPolicy(<Cno~o>)- n.
n

QtCore. Qt:

NoFocus- - n ;

TabFocus- 1 - <>;

C1ickFocus- 2 - n 1 ;

StrongFocus- 11- <> ;

Whee1Focus- 15- n <>,


;

+
+

focusPo1icy () - ;
grabKeyboard () -

. n -

re1easeKeyboard ();

re1easeKeyboard () - .

, ,

focusWidget () QApp1ication. n ,

None.

QWidget.
n :

+
+

focusinEvent (self, <event>)- n ;


focus0u1;Event (self, <event>) - .

<event> n QFocusEvent,
:

gotFocus () -

True, QEvent. Focusrn, Fa1se-

1ostFocus () -

True, QEvent. Focusout, 11 Fa1se-

reason () -

. -

<>

setFocus ().

21.14).

n , n
n. ,

<>.

21.

451

[~.~:'"~.~~ ?.~ :~~.: ::~~.~~~~~.~~.~~.~ . ~~.~.~~---- . . . . . . . . . . . . ;. . . . . . . . . . . . . .:. . . . . . . . . . . ,. .......................... .

. ...... i

# -*- coding: utf-B -*from PyQt4 import QtGui


class MyLineEditiQtGui.QLineEdit):
def
init lself, id, parent=None):
QtGui.QLineEdit. init lself, parent)
self. id = id
def focusinEventlself, ):
print 1" n", self. id)
QtGui.QLineEdit.focusinEventlself, )
def focusOutEventlself, ):
printi"oep n", self.id)
QtGui.QLineEdit.focusOutEventlself, )
class MyWindowiQtGui.QWidget):
def
init lself, parent=None):
QtGui.QWidget. init lself, parent)
self.resizeiOO, 100)
self.button = QtGui.QPushButtoni"Ycao
self.linel = MyLineEditll)
self.line2 = MyLineEditl2)
self.vbox = QtGui.QVBoxLayoutl)
self.vbox.addWidgetlself.button)
self.vbox.addWidgetlself.linel)
self.vbox.addWidgetlself.line2)
self.setLayoutlself.vbox)

2")

self.button.clicked.connectlself.on~clicked)

# n n <>
QtGui.QWidget.setTabOrderlself.linel, self.line2)
QtGui.QWidget.setTab0rderlself.line2, self.button)
def

on~clicked(self):

self.line2.setFocus()
if

n
main
import sys
= QtGui.QApplication(sys.argv)
window = MyWindow()
window. show 1)
sys.exlt(app.exec~() 1

21.9.2.

( "" )
(. <Ait> 11
<Ctl>) - .
( ). .

452

11.

, &

. , &, ,
.

<Ait>

. ,
, .
,

setBuddy ( <~>) QLabel.


QWidget:

i,

grabShortcut (<> [,

<>]) -

~, .
<11111> QKeySequence.

<Ait>+<E>

, , :

QtGui.QKeySequence.mnemonic("&e")
QtGui .QKeySequence ( "Alt+e")
QtGui.QKeySequence(QtCore.Qt.ALT + QtCore.Qt.Key_E)
<> WidgetShortcut, WidgetWithChildren-

Shortcut, WindowShortcut (
QtCore.Qt;

+
+

no

) ApplicationShortcut

releaseShortcut (<ID>) - <ID>;


setShortcutEnaed

( <ID> [,

<> J)

<>

True ( ),

<ID> . False .
QEvent. Shortcut,

+
+

event (self, <event>). <event>


QShortcutEvent, :

shortcutld () - ' ;
isAmiguous

() -

+ key ()

1 rue,

False-

QKeySequence.

, (

21.1 5).

(<Ait>+<E>)-

(<Ait>+<Y>)

(<Ait>+<B>)

grabShortcut ().

# -*- coding: utf-8 -*from PyQt4 import QtCore, QtGui


class MyLineEdit(QtGui.QLineEdit):
def
init (self, parent=None):
QtGui.QLineEdit. init (self, parent)
self. id = None
def event(self, ):
if e.type() == QtCore.QEvent.Shortcut:

21.

453

if se1f.id == e.shortcutid():
se1f.setFocus(QtCore.Qt.ShortcutFocusReason)
return True
return QtGui.QLineEdit.event(se1f, )
c1ass MyWindow(QtGui.QWidget):
def
init (se1f, parent=None):
QtGui.QWidget. init (se1f, parent)
se1f.resize(300, 100)
se1f .11 = QtGui. QLabe1 ( "& 1")
se1f.1ineEdit1 = QtGui.QLineEdit()
se1f .11. setBuddy (self .1ineEdi t1)
se1f.1ineEdit2 = MyLineEdit()
se1f.1ineEdit2.id = se1f.1ineEdit2.grabShortcut(
QtGui.QKeySequence.memonic("&e"))

se1f.button = QtGui.QPushButton("&Ypa
se1f.vbox = QtGui.QVBoxLayout()
se1f.vbox.addWidget(se1f.label)
se1f.vbox.addWidget(se1f.1ineEdit1)
se1f.vbox.addWidget(se1f.1ineEdit2)
se1f.vbox.addWidget(se1f.button)
se1f.setLayout(se1f.vbox)
se1f.button.c1icked.connect(self.on_c1icked)
def on_c1icked(self):
se1f.1ineEdit1.c1earFocus()
if

1")

n
main
import sys
= QtGui.QApp1ication(sys.argv)
window = MyWindow()
window. show ()
sys.exit(app.exec_())

QShortcut. 1

se1f.1ineEdit2 = QtGui.QLineEdit()
self.shc = QtGui.QShortcut(QtGui.QKeySequence.memonic("&e"), self)
se1f.shc.setContext(QtCore.Qt.WindowShortcut)
self.shc.activated.connect(self.lineEdit2.setFocus)
QAction.
:.

se1f.1ineEdit2 = QtGui.QLineEdit()
se1f.act = QtGui.QAction(se1f)
self.act.setShortcut(QtGui.QKeySequence.memonic("&e"))

se1f.act.triggered.connect(se1f.1ineEdit2.setFocus)
se1f.addAction(se1f.act)

454

21.9.3.

11.

n :

keyPressEvent (self, <event->) - n .


, n, n
n;

keyReleaseEvent (self, <event>) - n n .

<event> n n QKeyEvent, n n
QKeyEvent

n .

(n ; n n

no

QKeyEvent):

key () - . n :
if e.key()

==

QtCore.Qt.Key_B:

print("Haaa

text () -

<>")

Unicode.

n, n ;

modifiers () -

<Ait>

n n, -

(<SI1ift>, <Ctrl>,

.) .

QtCore .Qt ( ):

NoModifier- ;

ShiftModifier-

ControlModifier-

AltModifier-

MetaModifier-

Keypadodifier- n ;

GroupSwitchodifier-

<Shift>;
<Ctrl>;

<Ait>;

<Meta>;
<Mode_switch>

( 11 ).

<SI1ift>:

if e.modifiers() & QtCore.Qt.ShiftModifier:


print (" <Shift>")

isAutoRepeat () -

rue, n

False- n ;

matches ( <QKeySequence. StandardKey>) -

True, n

, , False- n
. QKeySequence,
n, QKeySequence.Copy 11

<Ctri>+<C>

(n).

QKeySequence. :

if e.matches(QtGui.QKeySequence.Copy):
print (" <Ctrl>+<C>")
, :

n n . n
n

no

, n n.

21.

455

, setFocusPolicy (<>),
.

21.9.1;

grabKeyboard (), - releaseKeyboard ();

<Shift.>+<Tab>.

<>

event (self, <event>);

, accept () .
,

21.10.

accept ()

ignore ( J.

, .
,
I, .
, ,

.
, .

21.1 0.1.

mousePressEvent (self, <event>) - ;

mouseReleaseEvent (self, <event>) -


;

mouseDoueClickEvent

(self,

<event>)-

. ,

. :
~
~

MouseButtonPress
MouseButtonRelease

MouseButtonDClick

MouseButtonPress
MouseButtonRelease

: setDoueClickinterval ()

QApplication.

douleClickinterval().

<event> QMouseEvent,

. QMouseEvent t~.
:

()

() -

pos () - QPoint
11 ;

11. 1

456

posF () -

QPointF

globalX () global () -
;

+
+

globalPos () - QPoint ;
button () -

, .

QtCore.Qt:

NoButton- - . button ()

LeftButton- 1 -

RightButton- 2 -

MidButton

XButtonl-

XButton2- 16;

buttons () -

MiddleButton- 4 -

, .

LeftButton, RightButton MidButton.


:

if e.buttons() & QtCore.Qt.LeftButton:


print (" I")

modifiers () -

<Ait>

, -

(<SI1ift>, <Ctrl>,

.) .

2 1.9.3.

~, accept () .
, accept ()

ignore ().

WA_NoMousePropagation QtCore.Qt

, .

setAttribute ():

self.setAttribute(QtCore.Qt.WA_NoMousePropagation, True)
,
. ,

21.1 0.2.

grabMouse ().

re1easeMouse ().

mouseMoveEvent (self, <event>). <event>


QMouseEvent, .
. ,

button () QtCore .Qt .NoButton.

mouseoveEvent () ,

- n . ,

21.

457

.
,

setMouseTracking () QWidget 1 True.

grabMouse ().

pos ()

.
,

QWidget:

mapToGlobal (<QPoint>) -

. QPoint;

mapF'romGlobal (<QPoint>)-
. QPoint;

mapToParent (<QPoint>)-
.
,

mapToGlobal ().

QPoint;

mapF'romParent ( <QPoint>) -

.
, 1

mapFromGlobal ().

QPoint;
<QPoint>)-
<QWidget>.
QPoint;

mapTo(<QWidget>,

mapF'rom ( <QWidget>, <QPoint>) - l<


<QWidget> .
QPoint.

21.1 0.3.

:

enterEvent (self,

<event>) -

leaveEvent (self,

<event>) -

<event> QEvent.

. ,
.

21.10.4.

wheelEvent (self,
<event>). <event>
QWheelEvent, .

458

11.

QWheelEvent :
.

delta () -

orientation ()

QtCore. Qt:

Horizontal- 1 -

Vertical- 2 -

()

() -

pos () - QPoint
;

globalx () global () -

globalPos () - QPoint
;

buttons () .

'l

LeftButton, RightButton

MidButton. :
if e.buttons() & QtCore.Qt.LeftButton:
print (" I")

modifiers () -

<Ait>

, -

~ .

(<SI1ift>, <Ctrl>,

.) .

21.9.3.

accept () .

, accept ()

21.1 0.5.

ignore () .

QWidget:

setCursor(<ypcop>)- .
QCursor
QtCore. Qt: ArrowCursor ( ), UpArrowCursor (,
),
CrossCursor ( ), WaitCursor ( ),
IBeamCursor (1- ), SizeVerCursor (,.
), SizeHorCursor (, ), SizeBDiagCursor (,
), SizeFDiagCursor (,
), SizeAllCursor (,

,
,

),
BlankCursor ( ),
SplitVCursor ( ), SplitHCursor (
), PointingHandCursor ( ), ForiddenCursor ( ),
OpenHandCursor ( ), ClosedHandCursor ( ), WhatsThisCursor
( ) BusyCursor ( ).

21.

459

self.setCursor(QtCore.Qt.WaitCursor)

+ unsetcursor ()

- .

+ cursor () - QCursor .

1

setOverrideCursor (<>) -

QApplication:

QCursor
QtCore. Qt.
restoreOverrideCursor();

restoreOverrideCursor () -

. :

QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
# m n
QtGui.QApplication.restoreOverrideCursor()

changeOverrideCursor(<ypcop>)-
.

setOverrideCursor (),

QCursor QtCore.Qt;

+ overrideCursor ()

- QCursor -

None.


, - ,
.

, (

Wai tCursor ).
setOverrideCursor () .
.

restoreOverrideCursor ()

, .

setOverrideCursor ()

restoreOverrideCursor ()

QCursor .
, QPixmap.
, QCursor

QPixmap, - ""

. :

self. setCursor (QtGui .QCursor (QtGui .QPixmap ( "cursor .png"),

0))

QCursor :

pos () -

QPoint

. :

print(QtGui.QCursor.pos()

.(),

QtGui.QCursor.pos()

.())

setPos () . :
setPos ( <>, <>) set Pos ( <QPoint>).

460

21.11.

drag & drop

11.

drag & drop

r>

: , ,
.

Windows.

, ,
, . ' , ,.

, ,

<Ctrl>.

21.11.1.

. . ,
.
., .
:

\.

mousePressEvent ()

2.

mouseoveEvent

()

. ,
.

QApplication:

startDragDistance () -

setStartDragDistance (<>)
startDragTime () -

- ;

3.

setStartDragTime (<>)

- .

QDrag

_ (),

, (,

).

. QDrag :
<>

QtGui.QDrag(<Ccma

>)

QDrag :

() -

. :
_([<>=vtin])
_(<>,

<

>)

<> ,
< >- , ,.

.
QtCore.Qt: CopyAction (1; ), MoveAction (2; ), LinkAction
( 4; ). IgnoreAction (; ), TargetMoveAc~:ion ( 32770 ).

21.

461

act = drag.exec_(QtCore.Qt.MoveAction 1 QtCore.Qt.CopyAction,


QtCore.Qt.MoveAction)

start ( [ <>=tin] ) , n

no

n ;

n. n -

setMimeData (<QMimeData>) -n n .
n QMimeData. n :
data = QtCore.QMimeData()
dt.stt(" ")

drag = QtGui.QDrag(self)
drag.setMimeData (data)

+
+

mimeData () - n QMimeData n ;
setPixmap ( <QPixmap>) - , n
QPixmap. :

. n n

drag .setPixmap (QtGui .QPixmap ("pixmap.png"))

pixmap () - n QPixmap , n
;

setHotSpot (<QPoint>) - "" n


QPoint. :

. napal\.1epa n

drag.setHotSpot(QtCore.QPoint(20, 20))

hotSpot () -

QPoint

""

n ;

setDragcursor (<QPixmap>, <>) - n


, n. n n
n QPixmap, n- CopyAction, oveAction
LinkAction. n n n QPixmap,
n .
n:

drag.setDragCursor(QtGui.QPixmap("cursor.png"),
QtCore.Qt.MoveAction)

+
+

source ()

- n-;

target () -

n-n

None,

n-

n.

+
+

QDrag

n :

actionChanged (Qt:: DropAction)


targetChanged (QWidget

- n ;

*) - n n n.

self.connect(drag, QtCore.SIGNAL("actionChanged(Qt::DropAction)"),
self.on_action_changed)
self.connect(drag, QtCore.SIGNAL("targetChanged(QWidget *)"),
self.on_target_changed)

462

21.11.2.

11.

QMimeData

I-

QimeData.

setMimeData ()

QDrag. QMimeData :
data

QtCore.QMimeData()

QMimeData ( ; -,
QMimeData):

setext (<>) - (I-

text/plain).

dt.stt(" ")

+
+

text () - (I- text/plain);


hasext () -

True, ~

1
!

(I- text/plain), False- ;

setHtml (<L->) -
text/html). :

HTML (I-

dt.sttml("<> L-</>")

+
+

html () -
hasHtml 1)

HTML

(I- text/html);

HTML (I-

True,
text/html), False- ;

setUrls (<n URI-apeco>) URI-apeco (I-


text/uri-list). QUrl.
I- . ~1
:

data. setUrls ( [QtCore.QUrl ( "http: //google. ru/")])

urls 1) -

URI-apeco (I- text/uri-list).

~ URI-apeca:

uri

e.mimeData() .urls() [0] .toString()

hasUrls 1) -

True, URI-apeco

(I- text/uri-list), False- ;

setimageData (<
>)

(I-
application/x-qt-image). ,- ,
Qimage QPixmap. :
data. setimageData (QtGui .Qimage ( "pixmap.png"))
data. set ImageData (QtGui. QPixmap ( "pixmap. png") )

imageData () -

, setimageData () );

+
+

hasimage 1) - True, (I-


application/x-qt-image), False- ;
setData (<I->,

<>) -

I-. I- , -

21.

463

QByteArray .

I-. :

data. setData ( "text/plain",


QtCore.QByteArray(bytes

("",

"utf-8")))

data(<MIME-n>)-

QByteArray ,

I-;

hasFormat (<I-n>) I-,

True,
False- ;

+.

forinats () - I-;

removeFormat ( <I->) - , 1 -;

clear()- I-.

- ,

QMimeData retrieveData () formats ().


.

21.11.3.

,
, .

setAcceptDrops ()

QWidget

True:

self.setAcceptDrops(True)
:

1.

dragEnterEvent () I-

, .t1

acceptProposedAction ( J
setDropAction ( J
acceptProposedAction ().

. ,
,

2.

accept

(),

dragMoveEvent ().
t.

accept (),

QRect

. ,

dragMoveEvent () .

3.

dropEvent () .

, 11 ,
:

dragEnterEvent ( self,

dragLeaveEvent (self, <event>) -,

<event>

QDragLeaveEvent;

<event>) -

. <~vent> QDragEnterEvent;

dragMoveEvent (self,

<event>)-
<event> QDragMoveEvent;

464

/1.

dropEvent (self, <event>) - . <event> QDropEvent.

QDragLeaveEvent QEvent
. , .
:

(QEvent, QMirneSource) - QDropEvent - QDragMoveEvent - QDragEnterEvent

QMirneSource
. QMirneSource
QMirneData. QDragEnterEvent ,
QDropEvent QDragMoveEvent.

QDropEvent :

rnirneData () -

QMirneData

I-;

+
+

pos () - QPoint ;
possieActions () -

11.

if

& QtCore.Qt.MoveAction:

e.possieActions()

print ( "MoveAction")
if

+
+

& QtCore.Qt.CopyAction:
print ("CopyAction") .

e.possileActions()

proposedAction () - ;
acceptProposedAction ()

proposedAction ().
acceptProposedAction () ( accept ())
dragEnterEvent (), dropEvent () ;

setDropAction(<ece>)- .

dropAction () -

accept (), acceptProposedAction ();

, .

. ,

proposedAction (), setDropAction ();

keyboardodifiers () -

<Ctrl>, <Ait>

+
+

, -

(<Shift>,

.) .

21.9.3;

rnouseButtons () - , ;
source () -

, None.

QDragMoveEvent:

accept ( [ <QRect> J) - ,
.

QRect ,
;

ignore ( [ <QRect> J ) - ,
. QRect
, ;

465

21.

+ answerRect ()

QRect -

, , .

PyQt

n,

drag &

d,

, "", ,
n .

21.12.

drag & drop

. n , n
(w ) . t!

clipboard () QApplication:
clipboard

QtGui .QApplication.clipboard ()

QClipboard ( ;
n QClipboard):

setText (<> [, <>]) -

+ text ( [<>] ) - ;
+ text (<> [, <>]) - .

, - . <>

"plai" ( ), "html" ( HTML)


;

setMimeData ( <QMimeData> [, <>]) -

. QMimeData.

+
+

drag & drop

(. .

21. 11.2);

mlmeData ([<>])- n QMimeData;


clear ( [<>] ) - .

<> Clipboard (

no

), Selection FindBuffer QClipboard.

dataChanged ().

self.connect (QtGui.qApp.clipboard(), QtCore.SIGNAL("dataChanged() "),


self.on_change_clipboard)

21.1 3.

, .

, QObject,
eventFilter (self,

<>,

<event>). <>

, <event>- .

MouseButtoPress QMouseEvent, KeyPress

QKeyEvet.

eventFilter ()

466

/1.

True, , False- .
, <>:

class MyFilter(QtCore.QObject):
def
init (self, parent=None):
QtCore.QObject. init (self, parent)
def eventFilter(self, obj, ):
if e.type() == QtCore.QEvent.KeyPress:
if e.key() == QtCore.Qt.Key_B:
print (" <>
return True
return QtCore.QObject.eventFilter(self, obj, )

")

~ , ,

installEventFilter (), !

. :

self.label.installEventFilter(MyFilter(self.label))
installEventFilter () ,
. (> , n

. , .

, , n

eventFilter ().

removeEventFilter (<>).

, .

21.14.

QCoreApplication:

sendEven:

(<QObject>,

<QEvent>) -

postEvent (<QObject>, <QEvent>) - .


, , n

<QObject> , ,
<QEvent>- . n
(, QMouseEvent), n n
, QEvent. n
QEvent .MouseButtonPress label:

= QtGui.QouseEvent(QtCore.QEvent.MouseButtonPress,

QtCore.QPoint(S, 5), QtCore.Qt.LeftButton,


QtCore.Qt.LeftButton, QtCore.Qt.NoModifier)
QtCore.QCoreApplication.sendEvent(self.label, )
" ,

QEvent.

registerEventType () I
.

21.

467

class MyEvent(QtCore.QEvent):
idType = QtCore.QEvent.registerEventType()
def
init (self, data):
QtCore.QEvent. init (self, MyEvent.idType)
self.data = data
def ge~_data(self):
return self.data

MyEvent label:

Qtcore.QCoreApplication. sendEvent (self .label, MyEvent ( "512"))


customEvent (self, <event>).

event (self, <event>)

def customEvent(self, ):
if e.type() == MyEvent.idType:
self. setext (" : {0}". fonat

.get_data ()))

22

tt 3llt

, . ,

, tt 111111 , '!HaIIT,

t, 11 tt
.

PyQt

-, t

. . - , 11
, ii lt.

22.1.

-,
. .
,

10, 0).

11

!, , otii

11

tII. ii 11,
.
tt .
,

move (),

11

, ,

resize 1).
setGeometry 1).

, pmr).
t ,

II

20.3

20.-1.

t , 11 <J

11

,
(

22.1 ).

# -*- coding: utf-8 -*-

from PyQt4 import QtGui


1mport sys

22.

469

= QtGui.QApp1lcation(sys.argv)
window = QtGui.QWidget()
window. setWindowit1e (" ")
window.resize(OO, 120)
11 = QtGui. QLabe1 (" ", window)
button = QtGui.QPushButton("Tec ", window)
1abe1.setGeometry(10, 10, 280, 60)
button.resize(280, 30)
button.move(10, 80)
window. show ()
sys.exit(app.exec_())

n :

n n
n ;

n n n n
. , n n
, .
n , n n n n

, .


n. , n n
. ., n n.

22.2.

n- ( J/. , :.\t
) n.
n n,

. n , n
n n .
n n :

QHBoxLayout- n (
n). :
<>= QLut([<>])

QVBoxLayout- n (
). :
<>= QVLut([<>])

QHBoxLayout

QVBoxLayout

(QObject, QLayoutitem) - QLayout - QBoxLayout - QHBoxLayout


(QObject, QLayoutitem) - QLayout - QBoxLayout - QVBoxLayout
, QWidget,
, n .

470

11.

QVBoxLayout.

QHBoxLayout
setLayout ()

. , , :
.

QHBoxLayout :
window = QtGui.QWidget()
button1 = QtGui.QPushButton("1")
button2 = QtGui.QPushButton("2")
h = QtGui.QHBoxLayout()
hox.addWidget(button1)

#
#

hox.addWidget(button2)
window.setLayout(hox)

addWidget ()

- . :

addWidget(<Konoe>[,

stretch=O] [, alignment=O])

stretch , alignment-
.
:

hox.addWidget(button1,
hox.addWidget(button2,
hox.addWidget(button,

insertWidget () -

10, QtCore.Qt.AlignRight)
stretch=10)
a1ignment=QtCore.Qt.AlignRight)

insertWidget(<ec>,

<>[,

stretch=O] [, alignment=O])

, u

. ,
. .

addWidget ().

hox.addWidget(button1)

hbox.insertWidget(-1, button2) #
hox.i'nsertWidget (0, button)
#

+
+

removeWidget
addLayout () -

(<>) - ;

J< .

. :
addLayout(<Koeep>[,

insertLayout () -

stretch=O])

. ,
. :
insertLayout(<ec>,

<>[,

stretch=O])

22.

addSpacing (<>) -

471

n n

. :
hox.addSpacing(100)

insertSpacing [<>,

<>) -

n n

n n. n n

, n ;

n n

addStretch ( [stretch=OJ) -

stretch . n
n, n, n

stretch

n;

insertStretch[<ec>[,

stretch=OJ) - addStretch[),

n n. n n
, n .

a1ignment addWidget [) insertWidget () ~1 n

. n

QtCore.Qt:

AlignLeft- 1 - no ;

A1ignRight- 2 ~ no n ;

AlignHCenter- 4 - no ;

AlignJustify- 8 - n n;

AlignTop- 32- no ;

AlignBottorn- 64- no ;

AlignVCenter- 128- no ;

AlignCenter- AlignVCenter

no

AlignHCenter-

AlignAsolute- 16- setLayoutDirection ()

QWidget

QtCore .Qt. RightToLeft, AlignLeft

no n
no . AlignLeft
, AlignAsolute

, AlignRight-

A1ignLeft. nn AlignRight.
. n

. n, AlignLeft

AlignTop no

. n n .
, n (n
; n n ):

setDirection (<n>) -

n n. n

QBoxLayout:

LeftToRight- - n ( no
);

RightToLeft -

1-

n ;

472

11.

ttm- 2 - (
);

+
+

BottomToTop- 3 -

setMargin (<n>)

- ;

setSpacing (<>)

22.3.

- .

J"!O

QGridLayout.

(QObject, QLayoutitem) - QLayout - QGridLayout


QGridLayout

r-1:

<>= QGridLayout([<Poe>])

.
,

window = QtGui.QWidget()
button1
QtGui.QPushButton("1")
button2
QtGui.QPushButton("2")
button

setLayout ()
QGridLayout

#
#

QtGui.QPushButton("")

button4
QtGui .QPushButton ( "4")
grid = QtGui.QGridLayout()
grid.addWidget(button1, , 0)
grid.addWidget(button2, , 1)
grid.addWidget(button, 1, 0)
grid.addWidget(button4, 1, 1)
window.setLayout(grid)

addWidget () -

:
addWidget(<Konoe>,

<>,

<>[,

addWidget(<Konoe>,

<>,

<>,

< >[,

alignment=O])
< >,

alignment=O])

,
,

. < >

, < >- . alignment


. ,
, . :

grid = QtGui.QGridLayout()
grid.addWidget(button1, ,
grid.addWidge~(button2,
grid.addWidget(button,

, alignment=QtCore.Qt.AlignLeft)
1, QtCore.Qt.AlignRight)
1, , 1, 2)
,

22.

473

addLayout () - .
:
addLayout(<Koeep>,

<>,

<>[,

addLayout(<Koeep>,

<>,

<>,

< >[,

alignrnent=O])
<

>,

alignrnent=O])

n n . n
n

addWidget ().

QGridLayout (n ;

n n ):

setRowMinimneight (<>,

<>) -

<>;

setColumninimumWidth(<ec>,

<>)-

<>;

+ setRowStretch (<>,

< >) -

<>;

setColumnStretch (<>,. < >) -

<>;

+
+

setMargin (<>) - n n;
setSpacing(<aee>)- n
;

setHorizontalSpacing(<aee>)- n
;

+
+
+

setVerticalSpacing (<>) - n ;
rowCount () - ;
columnCount () - .

22.4.

QFormLayout n .

. n n,
- , n, n. n
n, n n, &
n n. n

( <lt>+) n, n n n
. :

(QObject, QLayoutitem) - QLayout - QFormLayout


n QFormLayout :
<>= QFormLayout([<Poe>])

n n. n
, setLayout ()
n.

474

QFormLayout

11.

window = QtGui .QWidget ()


lineEdit ; QtGui .QLineUjit()
textEdit ~ QtGui . QextEdit()
buttonl = QtGui.QPushButton("O&pa")
button2 = QtGui.QPushButton ( "O&c " )
h = QtGui.QHBoxLayout( )
hox.addWidget(buttonl)
hox.addWidget(button2)

form = QtGui.QFormLayout()
form.addRow ( "&Haae:", lineEdit)
form . addRow ( "& : ", textEdi t)
form.addRow(hox)

window.setLayout (form)
.

22.1.

22.1.

QE'ormLayout

QFormLayout ( ;

):

addRow () - . :
addRow(<Tec >,

<n> )

addRow(<Tec n> ,

<> )

addRow(<Konoel> ,
addRow(<Konoe> ,

<n2>)
<>)

addRow(<Konoe>)
ddRw(<> )

< > , r -
&. 11 ,

. 11 1 (
<it>+)

QLabel,

n .

, n n

setBuddy () .

11 L. 11

, n ( ) ;

insertRow () -

n t il .

, otei1ttepa.

22.

475

insertRow(<ec>,

< >,

<>)

insertRow(<ec>,

< >,

<>)

insertRow(<ec>,

<!>,

insertRow(<ec>,

<>,

insertRow(<ec>,

<>)

insertRow(<ec>,

<>)

<2>)

<>)

setformAligrunent (<>) - .
.

22.2.

form.setFormAligrunet(

QtCore.Qt.AlignRight 1

QtCore.Qt.AligBottom)

setLabelAligrunent (<>) - .
.

22.2.

form.setLabelAligrunent(QtCore.Qt.AlignRight)

setRowWrapPolicy (<>) -

QFormLayout:

DotWrapRows- - ;

wrapLongRows- 1 -

- ;

WrapAllRows- 2 -

setfieldGrowthPolicy(<Pe>)- .
QF"ormLayout:

F"ieldsStayAtSizeHint- -
( sizeHint () );

ExpandingFieldsGrow- 1 - ,
QSizePolicy.Expanding QSizePolicy.MinimumExpanding,
.
;

AllNonfixedfieldsGrow- 2 - ( )
;

+
+

setMargin(<Ocy>)- ;

setSpacing (<>) -

setHorizontalSpacing(<aee>)-
;

setVerticalSpacing (<>) - .

22.5.

QStackedLayout QStackedWidget

QStackedLayout .

. :

(QObject, QLayoutltem) - QLayout - QStackedLayout

476

/1.

QStackedLayout :
<>= QStackedLayout([<Poe>])


. ,

setLayout ()

+
+

QStackedLayout :

setStackingMode (<>) - .
QStackedLayout:

stackOne- - ( );

StackAll- 1 -

stackingMode () -

addWidget (<>) -

insertWidget (<>,

<>)

. ;

+
+
+
+
+
+

removeWidget (<>) - ;
count () -

currentindex () - ;
currentWidget () - ;
widget (<>) - ,
, None;
setCurrentindex (int) -
. ;

setCurrentWidget (QWidget

*) - ,

. .

QStackedLayout :

currentChanged ( int)

widgetRemoved(int)

QStackedWidget , ,
. :

(QObject, QPaintDevice) - QWidget - QFrame- QStackedWidget


QStackedWidget :
<>= QStackedWidget([<Poe>])

QStackedWidget addWidget (), insertWidget (), removeWidget (),


count (), currentindex (), currentWidget (), widget (), setCurrent Index () setCurrentWidget (),

QStackedLayout. , QStackedWidget
:

22.

indexOf (<r>) -

477

_len _

r) -

len (), .

currentChanged ( int)

22.6.

widgetRemoved ( int).

QSizePolicy

, ,
,

sizeHint ().

QSizePolicy.
setSizePolicy ( <QSizePolicy>) QWidget,
sizePolicy () .

QSizePolicy :

<>= QSizePolicy([<pao >,


<

>[,

< >]])

, ,

sizeHint ().
QSizePolicy:

Fixed- ,
sizeHint ();

Minimum- , sizeHint (),


. ;

Maximum- , sizeHint (),


. ;

Preferred- , sizeHint (), ,


, ;

Expanding--;-- , sizeHint (), ,


. ,
k ;

MinimumExpanding- , sizeHint (),


. ,
;

Ignored- , sizeHint (), . , .

QSizePolicy

setHor i zontal flol icy (<


.

>)

setVert ica 1 Poli (<

>)

setVerticalStretch(<aop

setHorizontalStretch(<aop

>)

>)

478

11.

, ,

.
.

, .
rue

setHeightForWidth (<>). ,
heightForWidth (<>) .

22.7.

, .
. ,
. QGroupox.
:

(QObject, QPaintDevice) - QWidget - QGroupBox


QGroupBox :

<>

QGru([<>])

<>

QGroupBox(<Tec>[,

<>])

<> . .
<> , .
&, ,
. , &, ,
.

<Ait>

QGroupBox :r -
setLayout (). 1

window

mainox

radiol =
radio2 =
=
h

QGroupBox

QtGui.QWidget()
= QtGui.QVBoxLayout()
QtGui.QRadioButton("&a")
QtGui.QRadioButton("&He")

QtGui.QGroupBox("&B

= QtGui.QHBoxLayout()

hox.addWidget(radiol)

Python?") #

hox.addWidget(radio2)
box.setLayout(hox)

# m

mainox.addWidget(box)

window.setLayout(mainox)
radiol.setChecked(True)

#
#

22.2.

QGroupBox ( ;

):

+
+

22.

setTitle ( <>)

479

- n;

setAl ignmet (<>) -

11 11 n

1. n

113 QtCore . Qt : AlignLeft .

AlignHCenter AlignRight. :
box.setAlignment(QtCore . Qt . Al ignRi ght i

setCheckae (<>) - n <~

Ecm1

True, n

, n ,

, n nn 11.
;

"'
:J QGrotrp8ox

isCheckale () -

ralse -

+
+

rue, n,

n ;

setChecked (<>) - rue, .


n n , . f alse ;
isChecked () -

1t rue, ,

, , ~~

22.2. QGroupBox

set r lat (<>> -

ra l se -

ralse-

True,

i sflat <) - 11 rue, pa


KII , 11 false- ~ .

QGroupox :

t clicked < l= > -

n ,

n~. setChecked <>,


. n n 1

True,

. ra l s e - :

t toggl ed (bool) -

np~1 1111 ,

n. 111 n rue.

. false- .

22.8.

Qfr ame QWidget 11 t

1 . n,
n . t .
:

(QObject , QPaintDevice) - QWidget - QFrame

480

<~>

QFrame

parent

[,

flags=<T >])

QFrame([parent=<Poe>]

11.

None,

, . , ,

flags

, . , ,
, , .

flags,

20.2.

( ;

QFrame

):

set FrameShape (<>) QFrame:

NoFrame-

Panel- 2 -

WinPanel- 3 -

- ;

1 -

, ;
,

Windows.

2 .

HLine- 4 -

VLine- 5 -

Sty1edPane1- 6 -

. ;

, .

setFrameShadow (<>)
QFrame:

- .

P1ain- 16- ;

Raised- 32-

Sunken- 48-

setFrameSty1e (<>)

- .

frame.setFrameStyle(QtGui.QFrame.Panel

+
+

setLineWidth (<>)

QFrame

1. :

QtGui.QFrame.Raised)

- ;

setMidLineWidth (<>) -

22.9.

HLine

VLine.

QTabWidget.

.
.

22.

481

QabWidget :

(QObject , QPaintDevice) - QWidget -

QaWi~get

QaWidget :
<>= QWidgt([<>))

< > n.

, n . n n
QabWidget :

window : QtGu i .QWidget()


tab = QtGui . QaWidget{)
tab . addTab (QtGui . QLael ("

tab .addTaQtGui . QLae l ( "


tab .addTaQtGui . QLabel ("
tab .setCurrentindex{O)
v = QtGui .QVBoxLayout{)

1" ) ,
2" ),
3"),

" ..n
"
"

&1")
&2")
&3")

vbox . addWidget{ta

window.set Layout {vbox )


window . show {)
n .

22.3.

22.3. n QabWidget

QTaWidget (n ;
n n ):

addTab {) -

. -

. :
dd < n>,

< >)

dd{<n> ,

<Qicon> ,

< >)

n <n> n,
. n n

. < > ,
. &, n ,
n. , n
&, n, n n.

<Ait>

. <Qicon> n (n Qicon),
n .
16 3ak. 1349

482

11.

sty1e = window.sty1e()
icon = sty1e.standardicon(QtGui.QSty1e.SP_DriveNeticon)
tab.addTab(QtGui.QLabe1("Coepoe 1"), icon,
" &1")
:

icon = QtGui.Qicon("icon.png")
tab.addTab(QtGui.QLabe1("Coepoe

insertTab () -

1"), icon,

&1")

"

. :
insertTab(<ec>,

<n>,

< >)

insertTab(<ec>,

<n>,

<Qicon>,

t removeTab (<>) -

< >)

, ,

, ;

c1ear () -

, ,

, ;

setTabText

(<>,

< >)

t setE1ideMode (<>)

- ,

. .

QtCore.Qt:

+
+

ElideLeft -

ElideRight -

ElideMidd1e -

ElideNone -

tabText

- ;
;

1-

t ;

2-

3-

(<>)

stn(<>,

<Qicon>)-

. ~

Qicon;

setTabPosition(<o>) - .

North-

South- 1 -

West -

2 -;

East -

3 -.

QTabWidget:

-;
;

:
tab.setTabPosition(QtGui.QabWidget.South)

setTabShape (<>) - .
QTabWidget:

22.

483

Rounded- - ( );

Triangular- 1 - ;

setTabsClosae (<>) -

True,

.
taCloseRequested

setMovae (<>) -

( int);

True,

setDocumentModc (<>) - True,


;

setUsesScrollButtons (<>) -

True,

. , ,
,

. False ;

setTabTool Tip (<>,

<>)

setTabWhatsThis (<>, <>) -


;

setTabEnaed (<>,

<>) -

False,

~ .

True

isnd(<>)- rue,
,

count () -

False-

len ():

print(tab.count(), len(tab))

+
+

current1ndex () - 11...:;
currer\tWidget () -

widget (<>) -

None;

indexOf (<>) - ,
<>. ,

-1;

setCurrentindex ( int) ;

setCurrentWidget (QWidget *) - ,
. .

QTabWidget :

currentChanged ( int) -

. .

taCloseRequested

( int) -

484

11.

22.1 . ""

QToolBox n n .

, n .
, .
:

(QObject, QPaintDevice) - QWidget - QFrame

QToolBox :

<>= Ql([rnt=<>]

parent
flags

[,

flags=<Tn >])

n. n

QoolBox

None, n .

n . n Ql:

window = QtGui.QWidget()
toolBox = QtGui.QoolBox()
toolBox.additem (QtGui .QLabel (" 1"), " &1")
toolBox.additem(QtGui.QLabel("Coepoe 2"), " &2")
toolBox.additem(QtGui.QLabel("Coepoe 3"), " &3")
toolBox.setCurrentindex(O)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(toolBox)
window.setLayout(vbox)
window. show ()

QToolBox (n ; n

n ):

additem () -

. :
dditm(<>,

< >)

additem(<Konoe>,

<Qicon>,

<

>)

n <> n,
. n

. < > ,
. &, n ,
n. , n
&, n, n n.

<Ait>

<Qicon>

n
n (n

Qicon),

n ;

insertitem() -

n.

. ':

insertitem(<ec>,

<>,

<

insertitem(<ec>,

<>,

<Qicon>,

>)

< >)

removeitem(<ec>)- , n n,
, ;

22.

485

setitemText (<>, < >) -


;

i temext (<>) - ;
setitemicon(<ec>,

<Qicon>)-
.

Qicon;

setitemToolTip (<>, <>) -


;

set ItemEnaed (<>, <>) -

False,

:> .

True ;

isitemEnaed (<>) - True,


,

count () -

False-

len ():

print(toolBox.count(), len(toolBox))

currentindex () - ;

currentWidget () -

widget (<>) - ,
,

None;

indexOf (<>) - ,
<>. , -1;

setCurrentindex (int) -

setCurrentWidget (QWidget *) - ,
. .

currentChanged ( int).
.

22.11.
QSplitter ,
. :

(QObject, QPaintDevice) - QWidget - QFrame - QSplitter


QSplitter :
<>

QSplitter([parent=<Poe>])

<>

QSplitter(<Opea>[,

rnt=<>])

parent .
None, .
<> .

486

11.

Horizonta1 ( ) vertica1 ( ) QtCore .Qt.

, .

QSpli tter:

window = QtGui.QWidget()
sp1itter = QtGui.QSp1itter(QtCore.Qt.Vertica1)
1abell = QtGui. QLabe1 (" n 1")
112 = QtGui .QLabe1 (" n'j' 2")
1abe11.setFrameSty1e(QtGui.QFrame.Box
QtGui.QFrame.P1ain)
1abe12.setFrameSty1e(QtGui.QFrame.Box 1 QtGui.QFrame.P1ain)
sp1itter.addWidget(1ae11)

sp1itter.addWidget(1abe12)
vbox = QtGui.QVoxLayout()
vbox.addWidget(sp1itter)
window.setLayout(vbox)
window. show ()
QSp1itter i ( ;
):

+
+

addWidget (<n>) - ;
insertWidget (<>,

<n>) -

1i .

, n;

setOrientation (<>) -

n.

Moryr

~I Horizonta1 ( ) vertica1 ( )

QtCore. Qt;

setHand1eWidth (<>) - n-,


;

savestate () -

QByteArray .

(n, ), n

restoreState(<QByteArray>);

setChildrenCollapsie (<>) - Fa1se, n


.

, n;

setCollapsie (<>,

<>) -

Fa1se n <> n

n ;

setOpaqueResize (<>) - Fa1se,


n n n

n . n n
n ;

setStretchFactor (<>,

<>) -

setSizes (<>) -

n n,

- n n;

sizes () - ( ). :
print(sp1itter.sizes())

#:

[308, 15]

22.

count () -

487

len ():

print (splitter. count () , len ( splitter) )

widget (<>) -

indexof (<n>) -

None;

<n>. , -1.
splitteroved(int,int).

:r : , -
.

22.12.

QScrollArea .
, .

. :

(QObject, QPaintDevice) - QWidget - QFrame QAstractScrollArea

- QScrollArea

QScrollArea :
<>= QScrollArea([<Poe>])

QScrollArea ( ;
):

setWidget ( <>1 - ;

setWidgetResizae (<>)- True,


.

False

setAlignrnent (<>) -

. :

scrollArea.setAlignrnent(QtCore.Qt.AlignCenter)

ensureVisie (<>,

<> [, xargin=SO] [, yMargin=50]) -

(<>,

<>) xargin

ensureWidgetVisie (<> [,

yMargin;

xargin=50] [,

yMargin=50]) -

, <> ;

widget () - , ,
None;

takeWidget () -

. -

QScrollArea QAstractScrollArea (

; ):

horizontalScrollBar ()
QScrollBar);

488

11.

verticalScrollBar () - n (n
QScrollBar);

cornerWidget () -

+
+

viewport () -

None;

setHorizontalScrollBarPolicy(<Pe>)-
n;

setVerticalScrollBarPolicy (<~) -

. <>

QtCore.Qt:

ScrollBarAsNeeded- - ,
;

ScrollBarAlwaysOff- 1 - ;

scrollBarAlwaysOn- 2 - ;

setViewportMargins (<>, <>, <n>, <>) -

i . ~.

23

QWidget.

QObject

, t ,

, . ,

, ., .
,

. .
,
.

23.1.

,
,
, . ,

HTML,

QLabel.

PyQt

CSS,

(QObject, QPaintDevice) - QWidget - QFrame - QLabel


QLabel :

<>= QLabel([parent=<Poe>]
<>= QLabel(<Tec>[,

parent

[,

flags=<Tn >])

rnt=<>]

[,

flags=<Tn >])

None,

flags.

<>

, . :

label =

QtGui.QLabel("Tec n",

label.resize(OO,

flags=QtCore.Qt.Window)

50)

label. show ()

QLabel

( ;

):

setext (<>) - , .
,

css.

HTML,

490

11.

:
label.setText("Tec <>:</>")

r n

HTML

\n,

n <br>. :

label. setText ( "\n

")

&, n ,
n. , n &, n
, n n.

<Ait>

n,

setBuddy (), .

&, .

n n, & .
:

label = QtGui. QLabel ( "&JJ")


lineEdit = QtGui.QLineEdit()
label.setBuddy(lineEdit)

setText (const QString&);

setNum(<co>)- n 9
n.

setWordwrap (<>) -

setNum (int) setNum (doule);

True, n

. n ;

setextFormat (<>) - .

QtCore.Qt:

PlainText- - n ;

RichText- 1 - ;

AutoText

2-

n ( ).

Richext,

PlainText;

+
+

text () - n;
setAlignment (<>) - n. n
.

22.2.

label.setAlignment(QtCore.Qt.AlignRight

QtCore.Qt.AlignBottom)

setOpenExternalLinks (<>) - n 1 True,


n n , n
, . :

label. setText ('< href="http: 1 /google. ru/">


label.setOpenExternalLinks(True)

setBuddy ( <ti>) -

rr</>')

n n n.

n n, & n

.
n, n n;

setPixmap(<QPixmap>)- n n. n
n QPixmap.
setPixmap(const QPixmap&).

23.

491

:
11.

setpixmap (QtGui .QPixmap ("foto. jpg"))

+ setPicture (<QPicture>) -

QPicture. setPicture (const

QPicture&) ;

+ setovie (<QMovie>)

- .

QMovie. setMovie (QMovie *) ;

+ setSca1edContents (<>) -

True,

.
;

+ setMargin (<>) - ~
+ setindent (<>) -
. ,
, , . .;

+
+

c1ear () - . ;
setextinteractioFlags (<>) -

. (

1)

QtCore.Qt:

NoTextinteraction-

extSe1ectaeByouse- 1 - ;

TextSelectaeByKeyboard-

2-

. ;

LinksAccessieByouse-

4-

LinksAccessieByKeyoard-

8-

<>,

TextEdi t- 16-

TextEditorinteraction-
TextSe1e~taeByMouse

1 TextSe1ectaleByKeyboard

1 TextEditae;

TextBrowserlnteraction-
TextSe1ectaeByMouse

<Enter>;

LinksAccessileByouse

setSe1ection (<>, <>) -

LiksAccessieByKeyboard;

<>,

<>;

se1ectionStart () ,--
-1, ;

+
+

se1ectedText () - ;
hasSe1ectedText () True,
, Fa1se- .

492

+
+

11.

QLabel :

linkActivated(const QString&)- n n n.

n n URL-apec;
linkHovered (const QString&) - n
. n n URL-apec
.

23.2.

n n.
n n - ~. n

QPusl')Button. :

(QObject, QPaintDevice) - QWidget


<>

QAstractButton

- QPushButton

QPushButton :

QPushButton([parent=<Poe>])

<>

QPushButton(<Tec>[,

<>

QPushButton(<Qicon>,

rnt=<>])

<>[,

rnt=<>])

parent n. n

None, n .
<> n , ,

<Qicon> .
QPushButton QAstractButton (
; ):

setText (<>) -

, n.

&, ,
n. , &, n,

n.

<Ait>

n . &,
;

+
+

text () -

, ;

setShortcut (<QKeySequence>) - .
:

button. setShortcut ( "Alt+B")


button.setShortcut(QtGui.QKeySequence.mnemonic("&B"))
button. setShortcut (QtGui . QKeySequence ( "Al t +") )
button.setShortcut(
QtGui.QKeySequence(QtCore.Qt.ALT + QtCore.Qt.Key_E))

+
+

seticon (<Qicon>) - ;
seticonSize (<QSize>) - .
QSize. seticonSize (const QSize&);

setAutoRepeat (<>) - n True,


clicked () , n
. n, n:

23.

493

animateClick ( [<> J) -

. .
,

100 .

click () - . ;

toggle () -

. ;

setCheckae (<>) -

True,

, -
;

setChecked (<>) -

True,

setChecked (bool);

isChecked () .,...- True,


False- ;

setAutoExalusive (<>)- rue,


- ;

setDown (<>) -

rue,

isDown () False -

True, ,

False setEnaed () QWidget.


isEnaed

True,

().
False- .

QAstractButton :

+
+
+

pressed () released () -

;
;

clicked(bool=O)- ,
. ;

toggled (l;_ol) -

. -

QPushButton (

; ):

setFlai: (<>)- True,


;

setAutoDefault (<>) - True,


<Enter>,

. <>.

True,

False;

setDefault (<>) - .
l .

<Enter>,

, ;

494

11.

setMenu(<Qenu>)- ,
. QMenu;

+
+

menu () - None;
showenu () - . .

23.3.

( )

n.

n. n

, n . n

n ri n QGroupBox,
. 22. 7, QButtonGroup.
QRadioButton. :
(QObject, QPaintDevice) -

QWidget -

QAstractButton

QRadioButton

QRadioButton :
<>= QRadioButton([parent=<Poe>])
<>= QRadioButton(<Tec>[,

rnt=<>])

QRadioButton QAstractButton (. .

23.2).

setChecked (),

isChecked (), ,
toggled (bool). n
.

23.4.

n - n n
n : ,

. QCheckBo~ :

(QObject, QPa