Está en la página 1de 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, QPaintDevice) -

QWidget -

QAstractButton

QCheckBox

QCheckBox :
<>

= QCheckBox (

[rnt=<> ]")

<>= QCheckBox(<Tec>[,

rnt=<>])

QCheckBox QAstractButton (. .

23.2),

setCheckState (<>) -

. .

QtCore. Qt:

+
+

unchecked- - ;

PartiallyChecked- 1 - ;

Checked- 2 -

checkState () -

;
;

setTristate ( [ <>=ru]) - rue (


), n .
;

23.

+ isTristate ()

True, n ,

- n .

False

495

<1

stateChaged ( it). n n .
n , n ,
n setChecked (), n n
isChecked (), n
toggled(bool). n n

23.5.

n n
r . n

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

drag & drop,

n, .
n n QLineEdit. :

(QObject,

QPaitDevice)

- QWidget - QLineEdit

QLieEdit :
<>~ QLineEdit([paret=<Poe>])

<>= QLineEdit(<Tec>[,

rt=<>])

n paret n. n

None, n .
<> n ,
n.

23.5.1.
1

QLineEdit ( ;
):

setEchoMode (<>) -

QLineEdi t:

Nonnal- - ;

NoEcho- 1 -

Password- 2 -

*;

PasswordEchoOnEdit- 3 - ,

*;
,

setCompleter ( <QCompleter>) -

. 1
QCompleter. :
lieEdit

arr =

= QtGui.QLineEdit()

[''",

'''',

''",

""]

496

11.

completer = QtGui.QCompleter(arr, window)


lineEdit.setCompleter(completer)

setReadOnly (<>) - rue,


;

+
+
+
+

isReadOnly () True,
False- ;
setAlignment

(<>) - ;

setaxLength (<>) - ;

setFrame (<r>) - False,


;

setDragEnaed (<>)

True,

.
;

setPlaceholderText (<>) -

, ;

setText (<>) - . :r
(const QString&);

setext

insert (<>) - .
, ;

+
+

text () -

, ;

displayext

() -

, .

setEchoMode (), ,

Password *;

+
+
+

selectedText () - ;
clear () - . ;
backspace () - . ,
, ;

del_ () - . ,
, ;

setSelection(<ec>,

<II>)- <>,

<>. ;

+
+

selectAll () - . ;
~electionStart ()

+
+
+
+
+

-1,

hasSelectedText () - True, , False ;


deselect ()

- ;

setCursorPosi tion (<>) - ;


cursorPosition () - ;
cursorForward (<> [,

steps=l J ) -

rue, ;

23.

cursorackward (<>

[,

497

steps=l] ) -

True, :r;

cursorWordForward (<>) -

rue, ;

cursorWordBackward (<>) -

True, ;

+
+

home (<>) - .
True, ;
nd(<>)- .

True, ;

cut () -

, ,

, Normal.
;

() -

, ,

Normal. ;

paste () - ,
, . ;
'

undo () - , ,
. ;

redo () -

. ;

isUndoAvailae () ,

True,

False -

isRedoAvailae

() -

True,
False- ;

createS1;:andardContextMenu () -

. ,

, QLineEdit,
contextMenuEvent (self, <event>).

.
QLineEdit :

cursorPositionChanged (int, int) - .


,
- ;

edi tingFinished () -

<Enter>

+
+
+

returnPressed () -

<Enter>;

selectionChanged () - ;
textChanged (const QString&) -

.
;

498

11.

textEdited (const QString&) -


. setext ().
.

23.5.2.

setinputMask (<>)

. ,

:
"<

>[;<->]"

+ 9- 9;
+ - , 9;
+ D - 1 9;
+ d - , 1 9;
+ - 1;
+ -, 1;
+ - (0-9, A-F, a-f);
+ h - , (0-9, A-F, a-f);
+ #-, ;
+ - ;
+ - , ;
+ N --'- 9;
+ n- , 9;
+ - ;
+ - , ;
+ > - ;
+ < - ;
+ ! - ;
+ \ - .

<

> , ,
. , . :
lineEdit.setinputMask("aa:

1ineEdit.setinputMask("aa:
1ineEdit.setinputMask("aa:

99.89.9999; ") #
99.89.9999;#") #
99.89.9999 .") #

_ _ __

##.##.####

hasAcceptaeinput ().
, rue,
-

Fa1se.

23.

23.5.3.

499

setva1idator (<QVa1idator>).
QVa1idator.

, :

+ QintVa1idator- .
. :

QintVa1idator([parent=None])
QintVa1idator(<Haaoe

>,

< >,

<>)

100:

1ineEdit.setVa1idator(QtGui.QintVa1idator(O, 100, window))

+ QDou1eVa1idator-

. :
QDou1eVa1idator([parent=None])
QDou1eVa1idator(<Haaoe
<

>,

<
>,

>,
<>)

, .

100. .

1ineEdit.setVa1idator(
QtGui.QDouleVa1idator(O.O,

100.0, 2, window))

ScientificNotation setNotation ().


StandardNotation, . :

Vd1idator =

QtGui.QDou1eVa1idator(O.O,

100.0, 2, window)

va1idatQr.setNotation(QtGui.QDou1eVa1idator.StandardNotation)

1ineEdit.setVa1idator(va1idator)

QRegExpVa1idator-
. ":

QRegExpVa1idator([parent=None])
QRegExpVa1idator(<QRegExp>, <>)

9:

va1idator = QtGui.QRegExpVa1idator(
QtCore.QRegExp("[0-9]+"), window)
1ineEdit.setValidator(va1idator)
, ,
$ .
hasAcceptaelnput

().

i , True,
-

Fa1se.

500

23.6.

11.

~
, HT~L.

& drop,

drag

. ~

QTextEdit.

(QObject, QPaintDevice) - QWidget - QFrame QAstractScrollArea

QTextEdit

<>

QTextEdit([parent=<Poe>])

<>

QTextEdit(<Tec>[,

parent

- QTextEdit

rnt=<>])

None,

<> HT~L,
.

QTextEdi t

HTML.

QPlainTextEdit,

23.6.1.

HTML

i I i .

QTextEdit ( ' ;

):

setext (<>) - .

HT~L. ~ sete;xt

+
+

(const QString&);

setPlainText (<>) -
setPlainText(const QString&);

. ~

setHtml (<>) -
setHtml (const QString&);

HT~L. ~

insertPlainText (<>) -

. , . ~

insertPlainText (const QString&);

insert]itml (<>) - HT~L


. , . ~
insertHtml (const QString&);

append (<>)

- HT~L -

+
+
+

setDocumentT i tle (<>)


documentTitle ()
toPlainText ()

- (

- (

<ti tle> );

<title>);

- , ;

23.

501

+ toHtml () - HTML;
+ clear () - . ;
+ selectAll () - . ;
+ zoomin ( [range=l)) - . ;
+ zoomOut ( [range=l]) - . ;
+ cut () - ,

, . ;

() -

, ,

. ;

paste () -

, . ;

canPaste () -

True, , False-

setAcceptRichText (<>) - True,


HTML
. False ;

acceptRic?Text () -

HTML,

True,

False- ;

undo () - , ,
. ;

redo () -

. ;

setUndoRedoEnaed (<>) - True,


,

isUndoRedoEnaed

'

() -

False- ;

True,

False- ;

createStandardContextMenu ( [ <QPoint> J ) -

.
, , QTextEdit,
contextMenuEvent (self, <event>).

ensureCursorVisie

() -

find (<> [, <> J) -

) . ,
rue, -

False.

<> (

QTextDocument:

Findackward- 1 - , ;

FindCaseSensi ti vely- 2 -

FindWholeWords- 4 - , ;

1)

502

print _ (<QPrinter>) -

11.

J:I .

QPrinter.

PDF:
printer = QtGui.QPrinter()
printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
printer. setOutputFileNarne ( "mypdf .pdf")
textEd~t.print (printer)

QTextEdit :
QTextCharFormat&)-

currentCharFormatChanged(const

. ;

+
+
+
+

cursorPositionChanged () - ;
selectionChanged () - ;
textChanged () -

copyAvailae (bool) -

. rue,
,

undoAvailae

False-

(bool) -

. rue,
,

redoAvailae

(bool) -

False-

. rue,
,

23.6.2.

False-

QTextEdit (

; ):

setTextinteractionFlags (<>) -
. (J1

1)

QtCore.Qt:

NoTextinteraction- - ;

extSelectaeByMouse- 1 - / ;

extSelectableByKeyboard-

2 -

. ;

LinksAccessileByMouse-

4-

LinksAccessileByKeyboard-

8-

. i

<>, i

extEditae-

16-

TextEditorinteraction-
TextSelectaeByMouse

<Enter>;

TextSelectaeByKeyboard

TextEditae;

23.

503

TextBrowserinteraction-
TextSelectaleByMouse 1 LinksAccessieByMouse 1

setReadUnly (<>) -

LinksAccessieByKeyboard;

rue,

isReadOnly () True, ,
F'alse -- ;

+ setLineWrapMode (<>) -

NoWrap-

WidgetWidth- 1 -

QTextEdit:

- ;
;

F'ixedPixelWidth- 2 -
() ;

, setLineWrapColnnOrWidth

F'ixedColnnWidth- 3 -
, setLineWrapColnnOrWidth ();

+
+

setneWrapColnnOrWidth (<>) - ;

setWordWrapMode (<>)- .
QTextOption:

NoWrap-

Wordwrap- 1 -

ManualWrap- 2 -

wrapAnywhere- 3 - ;

WrapAtWotdoundaryOrAnywhere-

;
;

4-

NoWrap;

, ;

setOverwriteMode (<>) - True,


. False ;

overwriteMode () - True,
F'alse- ;

setAutoF'onatting (<>) -

QTextEdi t:

AutoNone- ;

AutoBulletList-

AutoAll-
AutoBulletList;

*;

+
+

Qt

4.7

setCursorWidth (<>) - ;
setTaChangesFocus (<>) -

F'alse,

n <> . -.
True, <>
;

+
+

setTabStopWidth (<>) - ;
tabStopWidth () - .

504

23.6.3.

11.

QTextEdit (n ; n n
):

setCurrentFont (<QFont>) - .
setCurrentFont (const QFont&). n n
QFont. QFont :

<>= QFnt(<

>[,

pointSize=-1] [, weight=-1]

[, italic=False])
n n . n
pointSize . weight n
: 99 Light, Normal, DemiBold, Bold
Black QFont. n italic True,
;

currentFont 1) -

QFont

setFontFamily (< >) - .


setFontFamily (const QString&);

+
+

fontFamily () - ;
setFontPointSize (<>) - .
setFontPointSize (qreal);

+
+

fontpointSize () - ;
setFontWeight (<>) - .
setFontWeight (int);

+
+

fontWeight () -

setFontitalic(<a>)- n True,
.

fontitalic () -

setFontitalic (bool);

True, , False- n

setFontUnderline (<>) - n rue,


n. setFontUnderline (bool);

fontunderline () -

True, n, False- n

setextColor ( <QColor>) - .

QtCore. Qt (n, k, whi te . .) n

QColor (n, QColor("red"), QColor("#ffOOOO"), QColor(255,


setextColor (const QColor&);

,+
+

0) .).

textColor () - n QCo1or ;
setTextBackgroundColor (<QColor>) - .
QtCore.Qt (n, k, white . .) n "

QColor (n, QColor("red"), QColor("#ffOOOO"), QColor(255, , 0) .).


setTextBackgroundColor (const QColor&);

23.

505

+ textBackgroundColor () - QColor ;
+ setAlignrnent (<>) -
. .

22.2.

setAlignrnent (Qt: :Alignrnent);

alignrnent () - .

QTextCharFonnat,
.

setCurrentCharFonnat (<QextCharFonnat>).
currentCharFonnat ().

QextCharFonnat .

23.6.4.

QTextDocument

QTextDocument ,
. document ()

QextEdit.

seti?ocument (<QTextDocument>). :
QObject - QTextDocument
QTextDocument :
<>

QTextDocument([parent=<Poe>])

<>= QextDocument(<Tec>[,

rnt=<>])

parent . <>
~ ( L-),
.

QTextDocument ( ;
):

+
+
+
+

setPlainText (<>) - ;
setHtml (<>) -

HTML;

toPlainText () - , ;
toHtml ( [ <QByteArray> J ) -

HTML.

+
+

<meta>;

clear () - ;
lsEmpty () -

True, , False-

isModified () -

True, , False-

undo () ~ , ,
. ;

redo () -

. ;

isUndoAvailae () -" True,


,

False-

506

isRedoAvailale

() -

setUndoRedoEnaled (<>)

Fa1se -

11.

True,

isUndoRedoEnaled

() -

+
+

True,

Fa1se- ;

True,

Fa1se- ;

availaleUndoSteps

() - ;

availaleRedoSteps

() -

c1earUndoRedoStacks ( [stacks=UndoAndRedoStacks]) -

/ .

QTextDocument:

UndoStack-

RedoStack-

UndoAndRedoStacks- ;

print _ ( <QPrinter>) -

QPrinter;

find () - .
QTextCursor. , . ~
isNull () .
:

find(<Tec>[, position=O] [, options=O])


find(<QRegExp>[, position=O] [, options=O])
find(<Tec>, <QTextCursor>[, options=O])
find(<QRegExp>, <QextCursor>[, options=O])

<> , ~ <QRegExp>
.
,

position

<QextCursor>.

QtCore .Qt .caseinsensitive

setcaseSensiti vity (). options


(

1)

QTextoocument:

Findackward- 1 - , ;

FindCaseSensitive1y- 2 - .
;

FindWho1eWords- 4 - , ;

setDefau1tFont (<QFont>) - Lh .
QFont. QFont


:
<>= QFnt(< >[,

[, ita1ic=Fa1se])

pointSize=-1] [, weight=-1]

23.

507

n n . n

pointSize . n weight n
: 99 Light, Nonnal, DemiBold, Bold
Black QFont. n italic True,
;

setDefaultStyleSheet (<CSS>) - CSS


;

t
t
t

setDocumentMargin (<n>) - n n ;
documentargin

() - n ;

setaximumlockCount (<>)

. ,
n ;

maximumlockCount

t
t
t
t

charactercount () -

() -

Hnecount () - ;
ockCount

() -

firstlock

() -

QTextBlock,

lastBlock () -

n QTextBlock, n

findlock(<ec >)- QTextBlock,


, ;

f indBlockByNumer (< >) -

QTextBlock,

QTextDocument :

undoAvailae

(bool) -

. n True,
n ,

redoAvailae

(bool) -

False-

n . rue,
n n ,

False-

n .

undoCommandAdded ( ) -
;

ockCountChanged

( int) -

cursorPositionChanged(const

QextCursor&)-

- . , n
n ;

contentsChange (int, int, int) -

n ,
n- , -

508

+
+

contentsChanged () -

11.

:r ;

modificationChanged (1) - .

23.6.5.

QTextCursor

QTextCursor , .

QTextCursor :

QTextCursor()
QTextCursor(<QTextDocument>)
QTextCursor(<QTextFrame>)
QTextCursor(<QTextB1ock>)

<>
<>
<>

<>
<>

QextCursor(<QTextCursor>)

+
+

QTextEdit:

textCursor () (
QTextCursor). ,
setTextCursor ();
setextCursor

(<QTextCursor>) -

cursorForPosi t ion (<QPoint>) -

, .

QPoint ;

mvursr(<>[,
.

mode=MoveAnchor])-

QTextCursor:

NoMove -

Start -

Up- 2 -

StartOfLine- 3 -

StartOfB1ock- 4 -

StartOfWord- 5 -

PreviousB1ock- 6 - ;

PreviousCharacter- 7 -

Previousword- 8 -

Left- 9 -

WordLeft- 10-

End- 11 ___.:._

Down- 12 -

EndOfLine- 13- ;

EndOfWord- 14-

EndOfB1ock- 15 -

- ;

1-

;
;
;

;
;

;
;

23.

509

NextBlock- 16- ;

NextCharacter- 17

Nextword- 18 -

Right- 19-

wordRight -

- ;

20-

i NextCell, PreviousCell,
NextRow PreviousRow, .
mode
QTextCursor:

MoveAnchor- - ,
( );

KeepAnchor- 1 - .

QTextCursor ( :

n ):

isNull () -

True, (

),

setPosition(<o>[,

False- ;

mode=MoveAnchor])-

. .

+.

mode movecursor ()

QTextEdit;

movePosition(<o>[,

mode=MoveAnchor] [, n=1])-
mode i
movecursor () QextEdit. n
. <>

, ,

cur = textEdit.textCursor()
cur.movePosition(QtGui.QextCursor.NextCharacter,
mode=QtGui.QextCursor.MoveAnchor,

n=10)

textEdit.setTextCursor(cur)

movePosition () True,

. (

, - ), Fa1se;

+
+
+

position () - ;
positioninBlock () - ;

block () -

QTextBlock,

.ri, ;

+
+

blockNumer () -

atStart () ,

atEnd () ,

, ;

rue,
False- ;
True,

False-

510

11.

atBlockStart () - True,
False- ;

atBlockEnd () rue,
False- ;

select (<>) -
QTextCursor:

+
+

wordUnderCursor-

LineUnderCursor- 1 -

BlockUnderCursor- 2 - ;

Docurnent -

- , ;
;

- ;

hasSelection () - True, ,
False- ;
hasComplexSelection () -

True, False- :

, ,

+
+
+
+

clearSelection () - ;
selectionStart () - ;
selectionEnd () - ;
selectedText () -

. ,

, CTI'JOK

,

\u2029.

replace () :.
print (cur .selectedText (). replace ( ".\u2029", "\n"))

selection () - QTextDocurnentFragment,
. toPlainText () (
) toHtml () (

+
+

HTML)

removeSelectedText () - ~ ;
deleteChar () - , ,
;

deletePreviousChar()- ,

beginEditBlock () endEditBlock () -

, ;
.

undo ( )

redo ( ) ;

joinPreviousEdi tBlock () -
;

setKeepPositionOninsert (<>) - rue,


.
;

+
+

insertText (<> [, <QTextCharFormat>] ) -

insertHtml (<>) -

HTML.

23.

511

n insertBlock (), insertFragment (), insertFrarne (), insertimage (),


in::;ertList () insertTae () , n

mergeBlockCharFormat (), mergeBlockFormat () mergeCharFormat (). n

no

23.7.

QTextBrowser QTextEdit
n

no

n n .

(QObject, QPaintDevice) - QWidget -

QFr~e

QAstractScrollArea

QextEdit

QextBrowser

QextBrowser:
<>= QTextBrowser([parent=<Poe>])

QTextBrowser (n ;

n n ):

setSource(<QUrl>)- . n n~
QUrl. setsource (const QUrl&);

+
+
.+
+
+
+

source () - n QUrl ;
reload () -

n . ;

home () - n n . - ;
backward () - n . ;
forward () - . ;
backwardistoryCount () - ;

+ forwardHistoryCount () +

isBackwardAvailae () n ,

isForwardAvailae
n ,

+
+

;
rue, n

False-

() - True,
False- ;

clearHistory () - ;
historyitle (<>)

n ,

, - ,
n - ;

historyUrl (<>) - ,
URL-apec ( QUrl) , - URLapec , - URL-apec
;

setOpenLinks(<a>)- rue,

n no ( ). False
n.

512

11.

QTextBrowser :

anchorClicked ( const QUrl&) -

URL-apec ;

backwardAvailae (bool) -

. ;

forwardAvailae (bool) -

. ;

highlighted(const QUrl&)-
. URL-apec
( QUrl) ;

highlighted (const QString&) -


. tt URL-apec
;

+
+

historyChanged () - ;
sourceChanged(const QUrl&)- .

URL-apec .

QtWebKit,

QTextBrowser

23.8.

HTML, XHTML, CSS

JavaScript.

QSpinBox (

QDouleSpinBox ( ). ,

. :

(QObject, QPaintDevice) - QWidget (QObject, QPaintDevice) - QWidget -

QAstractSpinBox-

QSpinBox

QAstractSpinBox

QDouleSpinBox

QSpinBox QDouleSpinBox:
<>

QSpinBox([parent=<Poe>])

<>= QDouleSpinBox([parent=<Poe>])

QSpinBox

QDouleSpinBox

QAstractSpinBox ( ;
):

setButtonSymols (<>) - ,
.
QAstractSpinox:

UpDownArrows- - ;

. PlusMinus- 1 - +

-.

NoButtons- 2 - ;

23.

513

setAlignment (<>) - ;

setwrapping (<>) -

True,

n n, ,
;

setSpecialValueext (<>) -n ,
;

setReadOnly(<a>)- True,
;

setFrame (<>) - False, n


;

stepDown () - . ;

stepUp () - . ;

st(<>)- ( )

(n ) ;

'text () -

., ;

clear () - . ;

selectAll () - . .

QAstractSpinBox editingFinished (),

<Enter>.

QSpinBox QDouleSpinBox (
; ):

setValue (<>) .
setValue (int) setValue (doule);

value () - , ;

cleanext () - ;

setRange (<>,

<>), setMinimum (<>) setMaximum (<>) -

setPrefix (<>) - , n
;

setSuffix (<>) - ,
;

setSingleStep (<>) - , n
.

QDouleSpinBox setDecimals (<>),


.

QSpinBox QDouleSpinBox valueChanged(int) (


QSpinBox), valueChanged(doule) ( QDouleSpinBox) valueChanged(const
QString&), .
n n
.

17

1349

514

23.9.

11.

QDateimeEdit (
),

QDateEdit

( )

QTirneEdit

( ).

, .

. :

(QObject, QPaintDevice) - QWidget (QObject, QPaintDevice) - QWidget QDateEdit


(QObject, QPaintDevice) - QWidget -

QAstractSpinBox

- QDateTirneEdit
- QDateTirneEdit -

QAstractSpinBox

- QDateTirneEdit -

QAstractSpinBox

QirneEdit

:
<>= QDateTimeEdit([parent=<Poe>])

<>=

QDateTirneEdit(<QDateTirne>[, rnt=<>])
QDateTirneEdit(<QDate>[, rnt=<>])

<>

QDateTirneEdit(<Qirne>[,

<>

QDateEdit([parent=<Poe>])

<>

QDateEdit(<QDate>[,

<>

QirneEdit([parent=<Poe>])

<>=

<>= QirneEdit(<QTirne>[,

rnt=<>])

rnt=<>])

rnt=<>])

<QDateTirne> QDateTirne
datetirne Python. QDateTirne
datetirne toPyDateTirne ().
<QDate> QDate
date Python. QDate date
toPyDate ().
<Qirne>

QTirne tirne

Python. QTime tirne t

irne ( ) .

QDateTimeEdit QAstractSpinBox (. . 23.8)

(r ;
r ):

setDateTirne(<QDateTime>)- .
QDateTirne datetirne Pytln.
setDateTirne (const QDateTirne&);

.
t

setDate (<QDate>) - .
QDate date Python.
setDate (const QDate&);

setirne(<Qirne>)- .

QTirne tirne Python.


setTirne (const QTirne&);

dateTirne ()

date ()

QDateTirne

QDate

23.

515

time () - n QTime ;

setDateTimeRange (<>,

<>)

QDateTime datetime

setMinimumDateTime (<>)

Python;

setMaximumDateTime (<>) -

QDateTime ?atetime

setDateRange(<y>,

<>),

setinimumDate(<y>)

Python;

setaximumDate(<Macy>)

QDate date

setTimeRange (<>,
setMaximumTime (<>) -

<>),

setMinimumTime (<>)

. n

time

Python;

QTime

Python;

setDisplayFormat (<>)- 1 .
n , n .

dateTimeEdit. setDisplayFormat ( "dd.. HH:mm: ss")

setTimeSpec (<>) - .
LocalTime, u OffsetFromUTC QtCore.Qt;

setCalendarPopup (<>) -

True,

setSelectedSection (<>) -

NoSection, DaySection, MonthSection, YearSection, HourSection,

MinuteSection, SecondSection, MSecSection

+
+
+
+
+
+
+

AmPmSection

QDateTimeEdit;

setCurrentSection (<>) - ;
setCurrentSect ionindex (<>) - ;
currentSection () - ;
curr~ntSectionindex () - ;

sectionCount () - ;
sectionAt (<>) - n ;
sectionText (<>) - .

timeChanged(const
QTime&),
dateChanged(const
QDate&)

dateTimeChanged(const
QDateTime&). t1.
QDateEdit (n ) QTimeEdit (n )

QDateTimeEdit .

516

23.1 .

11.

QCa1endarWidget
. :

(QObject, QPaintDevice) - QWidget - QCa1endarWidget


QCa1endarWidget:

<>= QCa1endarWidget([parent=<Poe>])

QCa1endarWidget (
; ):

setSe1ectedDate (<QDate>) - .
QDate date

+
+

Python.

setSe1ectedDate (const QDate&) ;

se1ectedDate () - QDate ;
setDateRange (<>, <>), setMinirnumDate (<>) setMaximumDate
(<>) .
QDate date

Python;

setCurrentPage (<>, <>) -


. .

setCurrentPage(int,int);

+
+
+

monthShown () - ( 1 12), ;
yearShown () - , ;
showSe1ectedDate () -

. ;

showoday () -

. ;

showPreviousMonth () -

. t

. ;

showNextMonth () -

. n

. ;

showPreviousYear () -

. ;

showNextYear () - .
. ;

setFirstDayOfWeek (<>) - .
. ,
Monday QtCore. Qt;

setNavigationBarVisie (<>) - Fa1se,

setNavigationBarVisile(boo1);

setHorizonta1HeaderFonnat (<>) -

QCa1endarWidget:

23.

517

NoHorizontalHeader- - ;
SingleLetterDayNarnes- 1 -
;

ShortDayNarnes- 2 - ;

LongDayNarnes- 3 - ;

setVertica1HeaderFormat (<>) - .

QCalendarWidget:

NoVerticalHeader- - ;

rsoweekNumers- 1 - ;

setGridVisie (<>) - True,

;
setSelectionode (<>)

QCalendarWidget:

NoSelection- - ;
SingleSelection- 1 - ;

setHeaderTextFormat (<QTextCharFormat>) - .
QextCharFormat;

setWeekdayextFormat (<

>,

<QextCharFormat>)-

. Monday, uesday,

Wednesday, Thursday, Friday, Saturday Sunday


- QTextCharFormat;

setDateTextFormat (<QDate>,

<QTextCharFormat>) -

QtCore .Qt,

. QDate

date Pytho, - QTextCharFormat.


QCalendarWidget :

activated(const QDate&)-
<t>. ;

clicked(const QDate&)- .
;

currentpageChanged ( int, int) -

, - ;

selectionChanged () -

23.11.

QLCDNumer . ,
, .

, ,
. :

(QObject, QPaintDevice) - QWidget - QFrarne -

QLCDNumer

518

11.

QLCDNner:
<>
<>

QLCDNner([parent=<Poe>])

QLDNnr(< >[,

rnt=<>])

< > .
,

5.

QLCDNner ( ;
):

display (<>) -

, .

display(int),

display(doule)

display(const QString&);

checkOverflow(<co>)-

True,

, , .

+
+
+

intValue ()
value ()

False;

- ;

- ;

setSegrnentStyle (<>)- .
Outline, Filled Flat QLCDNner;

setMode (<>)

- .

QLCDNner:

- - ;

Dec- 1 -

Oct- 2-

Bin-

- .

setOctMode ()

setMode ()

setHexode

setBinode

(),

setDecode

(),

True,

() ;

setSmallDecimalPoint (<>)

( l
),

False-

( ).

setSmallDecimalPoint (bool);

setDigitCount (<>) -
setSmallDecimalPoint () False,

.
QLCDNner

overflow (),

, .

23.12.

QProgressar ,

.
:

(QObject, QPaintDevice) - QWidget - QProgressBar

23.

519

QProgressar:
<>= QProgressBar([parent=<Poe>])

QProgressBar ( ;
):

setValue (<>) setValue ( int) ;

value () - ;

text () - , ;

setRange (<>,

<>), setMinirnum (<>)

setMaxirnum (<>) -

. ,
,
.

setRange (int, int), setMinirnum(int)

setMaxirnum(int);

reset () - . ;

. setOrientat ion (<>) - .


Horizontal f! Vertical QtCore .Qt.
setOrientation (Qt: : Orientation);

setTextVisie (<>)- False,


;

setTextDirection (<n>) -

. ,

"windows", "windowsxp" "rnacintosh"

.
QProgressBar:

t torn- -

90

ottornToTop- 1 -

90

setinvertedAppearance (<>) - rue,


(,
, ).

valueChanged ( int) .

23.13.

QSlider ,
. :

(QObject, QPaintDevice) - QWidget -

QAstractSlider

- QSlider

QSlider:
<>= QSlider([parent=<Poe>])

<>= QSlidr(<>[,

rnt=<>])

<> .

Horizontal vertical ( ) QtCore.Qt.

11.

520

QSlider QAstractSlider (

; ):

stVlu(<>)-- . ~

setValue (int);

+
.+
+

value () -- ;
setSliderPosition (<>) -- ;
sliderPosition () -- .
( ),
,
,

value ()

sliderPosition ()

value ().
,

--, ;

setRange (<> 1

<>)

, setMinimurn (<>) setMaximurn (<>) -

setOrientation (<>) -- .
Horizontal Vertical QtCore.Qt;

setSingleStep (<>) -- ,
;

setPageStep (<>) -- ,

<Page Up>

<Page Down>,

setinvertedAppearance (<>) -- True,


(,
, );

setinvertedControls (<>) -- False,



<Page Up>

<Page Down>,

setracking(<a>)-- True,
( ).

valueChanged(int) .
False, valueChanged ( int)
;

hasracking () -- rue,
,

False--

QAstractSlider :

actionTriggered ( int) --:- ,


, ,

<Page Up>.

, SliderNoAction (),

SliderSingleStepAdd
(1),
SliderSingleStepSu
(2),
SliderPageStepAdd
(3),
SliderPageStepSu ( 4), SliderToMinimurn (5), SliderToMaximurn ( 6) SliderMove (7)
QAstractSlider;

rangeChanged ( int 1 int) -- .


,
~ ;

t
t

23.

521

sliderPressed () - ;
slideroved ( int) -

sliderReleased () - ;

valueChanged (int) -

QSlider ( ;
):

setTickPosi tion (<>) - .


QSlider:

NoTicks -

,icksBothSides- ;

TicksAove- ;

TicksBelow-

TicksLeft

TicksRight-

. ;

- ;
;

setTickinterval (<>) - 11 .

23.14.

QDial

QDial 1 (
),
. ,
- . :

(QObject, QPaintDevice) - QWidget

QAstractSlider

- QDial

QDial:

<>= QDial([parent=<Poe>])

QDial QAstractSlider (. .

23.1 3)

( ;
):

setNotchesVisie (<>) -

True,

. .
setNotchesVisie

(bool);

setNotchTarget (<>) -
. ;

setWrapping (<>) -

setWrapping(bool).

True,

522

11.

23.15.

QScrollar n n.

n,

n
n

n,

n,

n,

n . :

(QObject, QPaintDevice) - QWidget

QAstractSlider

- QScrollBar

QScrollBar:

<>= QScrollBar([parent=<Poe>])

<>= QSrllr(<>[,

rnt=<>])

<> n n n.

Horizontal Vertical ( )

QtCore.Qt.

QScrollBar QAstractSlider (. . 23.13)

n .

.
,

QScrollArea

(. .

22.12).

24

PyQt

n, n

n ( ), .
, ,

. n n "/n", n
, ~
n .

24.1.

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

(QObject, QPaintDevice) - QWidget -

QComoBox

Qm:
<>= Qm([rnt=<>])

24.1.1.

, , n n
QComoBox:

additern () - n. :
additem (<> [, <>] )
additem ( <QI con>, <> [, <>] )
n <> n, n

<Qicon>-

n . n <> n
n , n, ;

+
+

additems (<
insertitem() -

>) - n;

n n.

n. :
insertitem(<ec>,

<>[,

insertitem(<ec>,

<Qicon>,

<>])

<>[,

<>])

524

insertitems

(<>,

11.

<n >) -

. ;

+
+
+
+

insertSeparator (<>) - ;
setitemext (<>,

<>) - ;

setitemicon (<>, <Qicon>)

- ;

setitemData (<>,

[, role=UserRole] ) -

<>

. role ,
. ,

ToolTipRole QtCore.Qt,

,
. ;

setCurrentindex (<>)

+
+
+

currentindex () currentext

() -

setCurrentindex ( int);

itemext (<>) - ;
itmDt(<>[,

role=UserRole])-

role

<>;

count () -

len ();

+
+

removeitem(<ec>) - ;

clear () - .

24.1.2.

setEditale (<>) - rue,

<Enter>;

setinsertPolicy (<>) -

QComoBox:

Noinsert- - ;

InsertAtTop- 1 -

InsertAtCurrent- 2 - ;

InsertAtBottom-

InsertAfterCurrent -

InsertBeforeCurrent- 5 -

n;

- ;

4 -

;
;

InsertAlphabetically- -
;

setEditText (<>) - .
setEditText (const QString&);

t
t

24.

525

clearE:ditText () - nq . ;
setAutoComplet ion (<>) -

n True,

, ,
. False ;

n n ,

setCompleter (<QCompleter>) -

n . n
n

QCompleter;

setAutoCompletionCaseSensitivity(<Pe>)-
n . caseinsensitive

QtCore .Qt . Casesensitive

au~oCompletion () ,

True,

False-

n ;

setValidator (<QValidator>) -

n , QValidator (. .

setDuplicatesEnaed (<>) -

23.5.3);

n True,

n n . n
n;

setaxcount (<>)

n.

n ,
;

setaxVisieitems ,(<>) -

n;

setMinimumContentsLength (<>) -

setSizeAdjustPolicy (<>) - n
. n
QComoBox:

Adjustocontents- - ;

AdjustToContentsOnFirstShow- 1 - , n
n n n;

AdjustToMinimumContentsLength- 2 - AdjustToContents
AdjustToContentsOnFirstShow;

AdjustToMinimumContentsLengthWithicon-

- n

, n

setMinimumContentsLength (),

setFrame (<>) - n False, n


;

seticonSize (<QSize>) - ;

showPopup () - n;

hidePopup () - n.

526

11.

24.1.3.
n n n findText () (
) findData () (n ).
-1, . :
findText(<Tec>[,
findData(<ae>[,

f1ags=MatchExact1y
ro1e=UserRo1e] [,
f1ags=MatchExact1y

MatchCaseSensitive])
MatchCaseSensitive])

flags n. (
n

+
+

1)

QtCore. Qt:

MatchExact1y- - n n ;
MatchFixedString- 8 - n n , n
;

+
+
+
+
+
+
+
+

MatchContains -

1-

n n ;

atchStartsWith- 2 - n ;

MatchEndsWith- 3 - n ;
MatchRegExp- 4 -

n n ;

MatchWildcard- 5 - n ;
MatchCaseSensitive- 16- n ;
MatchWrap- 32 -

n ;

MatchRecursive- 64- n .

24.1.4.

Qm :

activated(int) activated(const QString&)- . n n n


( ) n. <t n
;

currentindexChanged (int) currentindexChanged (const QString&) - n


. n ( -1,
n n) ;

editTextChanged (const QString&) - n n.


n n ;

highlighted(int) highlighted(const QString&)-


n n. n .

24.2.

QFontComoBox n .
, n
, . :

(QObject, QPaintDevice) - QWidget -

QComoBox

QFontComoBox

527

24.

QFontComoBox:
<>= QFontComoBox([parent=<Poe>])

QFontComoBox QComoBox (. .

24.1)

+ setCurrentFont (<QFont>) -

.

m.

setCurrentFont (const QFont&). :

setCurrentFont (QtGui .QFont ( "Verdana"))

currentFont () QFont .
:
print(comoBo~.currentFont()

QFont.

.family())

setFontFilters (<>)- .

QFontComoBox:

AllFonts -

ScalaeFonts

NonScalaeFonts- 2 -

MonospacedFonts- 4 -

ProportionalFonts- 8 - .

1-

;
;

QFontComoBox

currentFontChanged (const QFont&),

QFont .

24.3.

, .
, ,
. (

QtCore .Qt):

+
+
+
+
+
+
+
+
+
+

DisplayRole ~- ( );
DecorationRole-- 1 - ( );
EditRole- 2 - , ;
ToolTipRole- 3 - ;
StatusTipRole- 4 - ;
WhatsThisRole- 5 - ;
FontRole- 6 - . QFont;
extAlignrnentRole- 7 - ;

BackgroundRole- 8 - . QBrush;
ForegroundRole- 9 - . QBrush;

528

CheckStateRole- 10- .

+
+
+

11.

QtCore. Qt:

Unchecked-

PartiallyChecked- 1 - ;

Checked- 2 -

AccessileTt;xtRole-

11 - n;

AccessileDescriptionRole-

12- n ;

SizeHintRole- 13- . n
QSize;

UserRole- 32 -

n , n

. , 32.
:
m.

setiternData (0, 50, role=QtCore ..Qt. UserRole)

m. setiternData (0,

" ",

role=QtCore.Qt.UserRole + 1)

24.4.

n n n "/
n", n n
. n :

- "" . ,
, n ;

- n .

- n n .
n, n
n n;

- n n.

n
n ;

- n , n

n . n
n n
. n

no

24.4.1.

n n QModelindex.
:

<>

= Qodelindex([<QModelindex

QPersistentModelindex>])

24.

529

, , .
, .

QModelindex
currentindex () QAstractitemView.

index ()

QModelindex :

isVa1id () -

True, , Fa1se-

+
+

data ( [Disp1ayRo1e]) - , ;

+
+
+

flags ()

Qtcore.Qt:
- ;

NortemFlags -

ItemisSe1ectae-

ItemisEditae-

ItemisDragEnaed-

4 -

ItemisDropEnaed-

8 - ;

ItemisUserCheckae- 16- ;

ItemisEnaed-

ItemisTristate- 64- ;

row () -

1 -

2 -

32- ;

co1umn () -

parent () - ( QMode1Index),
. ,

QModelindex;

chi1d(<Cpoa>,

<>)-

Qodelindex), .
, QMode1Index;

siing(<Cpoa>,

<>)-

Qodelindex), .
, QModelindex;

mode1 () - .

, QModelindex
.
,

QPersistentMode1Index,

, .

..

24.4.2. QStringListModel
QStringListMode1 , .

QListView, QComoBox .,

setMode1 (). :
QObject - QAstractiteffiode1 - QAstractListMode1 - QStringListMode1

530

<>

11.

QStringListModel:

QStringListModel([parent=<Poe>])

<>= QStringListModel(<Cco >[,

rnt=<>])

QStringListModel (
; ):

+
+
+

setStringList (< >)- ;


stringList ()
insertRows

- , ;

(<>,

<>

removeRows (<>,

<>

[, parent] ) -

[,

True,

parent]) -

, , .
rue, ;

setData ( <Qodellndex>, <> [, role=Edi tRole J )


role , <Qodellndex>.
rue, ;

data

(<Qodellndex>,

<>)

+
+

rowCount ( [parent])
sort

(<

<QModellndex>;

- ;

>[,

order=AscendingOrder])-

AscendingOrder QtCore.Qt,
,

DescendingOrder- .

QStringListModel index () QAstractListModel,

( QModellndex) . :
index(<Cpoa>[,

24.4.3.

column=OJI,

parent=Qodelindex()])

QStandardltemModel

QStandarditemodel () .

QStandarditem.
setModel ().

QTaleView, QreeView .,
:

QObject -

QAstractitemodel

QStandarditemodel

QStandarditemodel:
<>

QStandarditemodel([parent=<Poe>])

<>

QStandarditemodel(<Koeco >,

[,

< >

rnt=<>]

QStandarditemodel (
; ):

+
+
+

setRowCount (< >) - ;


setColumnCount (< >) - ;
rowCount ( [parent=Qodellndex ()]) - ;

24. i

531

+ colurnnCount ( [parent=Qodelindex () J ) - ;
+ setitem(<Cpoa>, <>, <QStandardrtem>)-
. :

model = QtGui.QStandarditemodel(, 4)
for row in range(O, 3):
for column in range(O, 4):
item = QtGui.QStandarditem(
"((0}, (l})".format(row, column))
model.setitem(row, column, item)
view.setModel(model)

+ appendRow (<n>) -

QStandarditem;

+ appendColurnn (<n>) - .

insertRow (< >, <>) .

QStandarditem;

<>

QStadarditem;

insertRow (<> [,

parent=Qodelindex () J ) -

insertRows(<ec>,

<>[,

True, ;

parent=QModelindex()J)-

. rue,
;

insertColurnn(<ec

>,

<>}-

. <>

QStandarditem;

isertColumn (<> [,

parent=Qodelindex () ] ) -

. rue, ;

insertColumns(<ec>,

<>[,

parent=Qodelindex()])-

. :r rue,
;

removeRows (<>,

<> [,

parent=QModel Index () ] ) -

, , <>.
rue, ;

rem?veColumns (<>, <>[, parent=QModelindex ()]) -


.[I , , <>.
rue, ;

+
+

takeitem (<> [, <>=]) -'-


( QStandarditem);
tkRw(<>)- (

QStandarditem);

takeColumn (<>) - ; (
QStandarditem);

clear () - ;

532

item(<Cpoa>[,

+
+

<>=])- (

invisileRootitem ()

QStandarditem),

11.

-
QStandarditem);

itemFromindex (<QModelindex>)
QStandardrtem), <QModelindex>;
index (<>,
(

<>

[, parent=QModelindex () ] ) -
QModelindex), ;

indexFromitem(<QStandarditem>)
QModelindex), ;

setData (<QModelindex>, <> [, role=EditRole]) role , <Qodelindex>.

rue, ;

+
+

data (<Qodelindex> [, role=DisplayRole])

- ,

<QModelindex>;

setHorizontalHeaderLabels (<

>)

setVerticalHeaderLabels (<

>) - .

setHorizontalHeaderitem(<ec>,

<QStandarditem>) -

QStandarditem;

setVerticalHeaderitem (<>, <QStandarditem>) -

QStandarditem;

hori zontalHeaderitem (<>) QStandarditem);

l(

verticalHeaderitem (<>) ( QStandarditem);

+
+

setHeaderData (<>,

<>,

<>

[, role] ) -

. ,

QtCore .Qt).

True,

headerData (<>,

role

orizon1oal

Vertical
EditRole.

<>[,

role])-

. ,

- .

finditems

(<>

[, flags=MatchExactly] [, column=O]) -
column .
. 24.1.3.
( QStandarditem) ;

role

DisplayRole;

flags

24.

533

sort (< > [,

order=AscendingOrder] ) .
AscendingOrder QtCore.Qt,
, DescendingOrder- ;

+
+

setSortRole (<>) - (. . 24.3), ;


parent (<QModelindex>) - ( QModelindex)

QModelindex) -;

hasChildren ( [parent=QModelindex () ] ) -

True,
E'alse-

, ,
.

itemChanged (QStandarditem *).

QStandarditem).

24.4.4. QStandardltem
QStandarditemodel

QStandarditem.

, )'.
:

<>

= QStandarditem()

<>

QStandarditem(<Tec>)

<>

= QStandarditem(<Qicon>,

<>
<>

<>)

QStandarditem(<Koeco >[,

< >=l])

= QStandarditem(<QStandarditem>)

QStandarditem ( . ;
):

+
+
+
+
+

setRowCount (< >) - ;


setColumnCount (< >) - ;
rowcount () - ;
columnCount () - ;
row () -
-1, ;

column () -
-1, ;

setChild (<>,

<>,

<QStandardrtem>) -

. :

parent = QtGui.QStandarditem(, 4)
parent. setext ("-")
for row in range(O, 3):
for column in range(O, 4):
item = QtGui.QStandarditem(
" ( {0}, {1}) ".format (row, column))
parent.setChild(row, column, item)
model.appendRow(parent)

534

n!Rw(<>) -

QStandarditem;

appenc!Row (<QStandarditem>) -

appendRows (<>) -

~ .

appendColUIIU1 (<>) -

insertRow(<ec >,
.

QStandarditem;

QStandarditem;

11.

QStandarditem;

<>) -.

<>

QStandarditem;

insertRow (< >, <QStandarditem>) -

QStandarditem;

insertRows (< >, <>) -


. <>

QStandardrtem;

insertRows (< >, <>) -


;

insertColum(<ec

>,

<>)-

. <>

QStandarditem;

insertColUIIU1s (<>,

<>) -

+
+

removeRow (<>) - ;
removeRows (<>, <>) - .
, <>;

+
+

removeColUIIU1 (<>) - ;
removeColUIIU1s (<>, <>) - ,
, <>;

takeChild(<Cpoa>[,

<>=])-

( QStandarditem);

takeRow (<>) -

!:.J

( QStandarditem);

takeColUIIU1 (<>) -
( n QStandarditem);

parent ()

QStandarditem) None;

child (<> [, <>=]) - (


QStandarditem) None;

hasChildren () 1 True, ,
F'alse- ;

24.

535

setData (<> [, role=UserRole+ 1]) - ;

data ( [UserRole+l]) - , ;

setext (<>) -

text () -

setextAlignment (<>) - ;

seticon ( <Qicon>) -

setool ip (<>) -

setWiiatsThis (<>) - ;

setFont (<QFont>) - ;

setBackground ( <QBrush>) - ;

, ;
;

setForeground ( <QBrush>) - ;
setCheckae (<>) - rue,
;

isChecka-e () -

rue,

, False -

setCheckState (<>) - .
QtCore.Qt:

unchecked-

PartiallyChecked- 1 - ;

Checked- 2 -

checkStaLe () - ;

setTristate (<>) -

rue,

~: , ;

isTristate () - True, ,
False- ;

setFlags (<>) - (. . 24.4.1);

flags () - ;

setSelectae (<>) - rue,


;

setEditae(<a>)- rue,
;

setDragEnaed (<>) - True,


;

setDropEnaed (<>) -

True,

setEnaed (<>) -
.

True,
False ;

clone () ----: ( QStandarditem);

536

+
+

11.

index ()'_ ( QModelindex);


model () - ( QStandardrtemodel);
sortChildren (<

>

[,

order=AscendingOrder]) -

QtCore. Qt,

AscendingOrder
DescendingOrder-

24.5.

ListView- , . , ;

+
+

QaleView- <l{l ;

QTreeView- .


QComoBox

24. /), QListWidget

),

QaeWidget () QTreeWidget ( ).
"/", . n
.

24.5.1.

QAbstractltemView

QAstractitemView i!.
:

(QObject, QPaintDevice) - QWidget - QFrame -

QAstractScrollArea

QAstractitemView

QAstractitemView (.h
; ):

setCurrentindex ( <Qodelindex>) (n

QModelindex)
.

setCurrentindex(const QModelindex&);

+
+

currentindex () - ( QModelindex) ;
setRootindex (<QModelindex>)

Qodelindex.

setRootindex(const QModelindex&);

rootindex () - ( QModelindex) ;
setAlternatingRowColors (<>) - True,
;

setindexWidget (<Qodelindex>,

<QWidget>) -

( QModelindex);

indexWidget (<QModelindex>) - ,
QModeiindex);

, (

24.

537

setSelectionodel (<QitemSe.lectionodel>)- ;

selectionodel () - ;

setSelectionode (<>) - .

QAstractitemView:

NoSelection- - ;
SingleSelection- 1

MultiSelection- 2 - .
;

ExtendedSe1ection- 3 - ,

<Ctrl>

<Shift>,

ContiguousSe1ection- 4 -

, .

<Shift>,

setSe1ectionBehavior(<Pe>)- .

QAstractitemView:

Se1ectitems- - ;

Se1ectRows- 1 -

Se1ectCo1umns- 2 - ;

t se1ectA11 ()

- . ;

t c1earSelection ()

- . ;

t setEditTriggers (<>)

- ,

.
QAstractitemView:

- ;

NoEditTriggers-

CurrentChanged- 1 -

Dou1eC1icked-

Se1ectedC1icked- 4 -

EditKeyPressed- 8 - <F2>;

AnyKeyPressed- 16- ;

AllEditTriggers- 31- ;

2 - ;

seticonSize (<QSize>) QSize;

setextElideMode (<>) -

. .
QtCore. Qt:

E1ideLeft- - ;

E1ideRight- 1 - ;

538

11.

2 - n;

ElideMiddle -

ElideNone- 3 - ;

setTabKeyNavigation(<a>)- n

True,

n n <>;

t.

scrollTo(<Qodelindex>[,

hint=EnsureVisie])- n n

, , (n QModellndex)

hint

QAstractitemView:

t
t

EnsureVisie- - ;

PositionAtTop- 1 - ;

PositionAtBottom- 2 - ;

Posi tionAtCenter- 3 - ;

scrollToTop () -

n n . ;
n n .

scrollToBottom () ;

setDragEnaed (<>) - n

True, n

setDragDropMode (<>) -

drag & drop.

QAstractitemView:

NoDragDrop-

DragOnly- 1 - n

oropOnly- 2 ~n ;

oragorop- 3 - n n ;

Internalove-

- drag & drop

n;
n;

4 -n , ;

set;DropindicatorShown (<>) -

True,

setAutoScroll (<>) - True,


n;

setAutoScrollMargin (<n>) -

n .
QAstractitemView :

activated(const Qodellndex&)- , ,
n <Eter>.
(n Qodellndex);

pressed (const Qodelindex&) -

. n n (
Qodelindex);

clicked (const QModelindex&) -

. n (n
QModelindex);

24.

+ dou1eC1icked(const

539

Qodelindex&)- n

. n n (n
QModelindex);

+ entered(const

Qodelindex&)- n

. , n
n setMouseracking () QWidget.
n n (n

+ viewportEntered () . .

QModelindex);

n n

, n

setMouseTracking ()

QWidget.

24.5.2.
QListView n n ,
n. , n .
:

(QObject, QPaintDevice) - QWidget - QFrame QAstractitemView

QAstractScro11Area

- QListView

QListView:

<>= QListView([parent=<Poe>])

QListView

(. .

24.5.1)

QabstractitemView

n (n

; n n ):

setMode1 (<>) - ; !

mode1 () - ;

setMode1Co1umn (<>) - ;

setViewode (<>) -

. n

QListView:

ListMode-

Iconode-

1 - n,

. n n ;

setMovement (<>) -

n . n

QListView:

static-

Free -

Snap- 2 - n

1-

- n n ;

n;

no

( setGridSize () );

setGridSize (<QSize>) - n ;
setResizeMode (<>) -

n. n QListView:
- n;

Fixed-

Adjust- 1 - n

n ;

540

setFlow (<>) -

11.

QListView:

LeftToRight-

- ;

Topoottom-

1 -

setWrapping (<>) -

False,

( ) ;

setWordWrap (<>) -

True,

setLayoutMode (<>) -

QListView:

SinglePass- - . ,
, ~ ;

Batched- 1 - .
setBatchSize (<>);

setUniformitemSizes (<>') - True,


;

+
+

setSpacing (<>) - ;
setSelectionRectVisie (<>) -

True,

,
.
;

setRowHidden (<>, <>) -

True,

, , . False
;

'

isRowHidden (<>) - rue,


False- ;

selectedlndexes () -

( Qodellndex) -

QListView indexesoved (const QModellndexList&),


.

24.5.3.

QModellndex.

QTaleView . :

(QObject, QPaintDevice) - QWidget - QFrame QAstractltemView

QAstractScrollArea

QaleView

QaeView:
<>= QTaleView([parent=<Poe>])

QTaleView
.

24.5.1)

QAstractitemView (.

; ):

24.

541

setModel (<>) - ;

model () - ;

horizontalHeader () -

(n

QHeaderView);

verticalHeader () -

(n

QHeaderView). n, :
view.horizontalHeader() .hide()
vi~w.verticalHeader()

.hide()

setRowHeight (<~<:>,

<>) - n n

setColunmWidth ( <~<:>,

<>) -

n ;

rowHeight (<~<:>) - ;

colunmWidth ( <~<:>) - ;

resizeRowoContents (<~<: J<:>) -


,

resizeRowoContents(int);

, n

resizeRowsToContents () -

. ;

resizeColunmToContents

(<~ >) -

, n .

resizeColunmToContents(int);

resizeColunmsocontents () -

, n

. ;

setSpan(<e~<:c J<:>,

<~<: >,

< ~<:>,

<

>) -

. ;

rowSpan ( <~<: J<:>,

<~<: >) -

colunmSpan ( <~<:

J<:>,

<~<:

>) -

, ;

clearSpans () - ;
setRowHidden ( <~<:>,

<>) - n True,

, n, . False
;

hideRow ( <~<:> J -

hideRow ( int);

showRow ( <~<:>) - .
showRow ( int);

setColunmHidden ( <~<:>,

<>) - n True,

, , . False
;

542

hideColwnn 1<>)

showColwnn (int);

isRowHiddeni<ec>)-

ralse-

True,

isColwnnHidden 1<>) ,

showColwnni<ec>)- .

hideColwnn 1int);

11.

ralse-

True,

isindexHiddeni<QModelindex>)-

True,

( Qodelindex) , E'alse- ;

selectRowi<ec>)- .

selectRow 1int);

selectColwnni<ec>)- .

selectColwnn 1int);
( QModelindex)

selectedindexes 1) -

~;

setGridStyle (<>) - .
QtCore .Qt:

NoPen-

SolidLine- 1 -

DashLine- 2 -

DotLine- 3 -

DashDotLine- 4 -

DashDotDotLine- 5 -

- ;
;

;
, . .;
, . .;

setShowGrid 1<>) - True,


,

ralse-

setShowGrid(bool);

setSort ingEnaed 1<>) -

rue,

.
;

setCornerButtonEnaed 1<>) - Tr:ue,


.

False

setWordWrap(<a>)- True,
;

sortByColwnn (< > [, AscendingOrder]) -

AscendingOrder QtCore. Qt,


, DescendingOrder- .

24.

24.5.4.

543

QTreeView . :

(QObject, QPaintDevice) - QWidget - QFrame QAstractitemView

QAstractScrollArea

QreeView

QreeView:
<>= QTreeView([parent=<Poe>])

. QTreeView

(. .

24.5.1)

; ):

QAstractltem~iew

( -

setModel (<>) -

11 ;

+ model () - ;
+ header () -

QHeaderView);

setColumWidth (<>,

<>) -

+
+

columWidth (<>) - ;

rowHeight ( <Qodellndex>) -

resizeColumToContents (<

>) -

QModellndex);

, .
resizeColumToContents

(int);

setUniformRowHeights (<>) -

True,

+
+

setHeaderHidden (<>) - rue,


. False ;
isHeaderHidden () -

True, , False -

setColumHidden (<>,

<>) - rue,

, , . False
;

hideColum (<>) -

hideColum

(int);

showColum(<ec>)- .
showeolum

isColumHidden (<>) ,

False -

( int);

True,

setRowHidden (<>, <Qodellndex>, <>) --;-


True, <> <QModellndex> .
False ;

isRowHidden (<>, <Qodellndex>) -

True,

<> <Qodellndex> ,
;

False -

544

isindexHidden ( <Qodelindex>) -

11.

True,

(n Qodelindex) , False- n 'l;

<>)

setExpanded (<QModelindex>,

rue, , n n

, , False- . n n
n Qodelindex;

expand ( <Qodelindex>)

n n

QModelindex. expand (const Qodelindex&);

expandToDepth (<>) -

+
+

expandToDepth (int);

expandAll () - . ;
collapse (<QModelindex>) - ,

n n

Qodelindex.

+
+

collapse (const QModelindex&);

collapseAll () - . ;

isExpanded ( <QModelindex>) -

True, ,

, , Fals~- n

. n n QModelindex;

setitemsExpandae (<>)

False,

n ;

setAnimated (<>) -

n rue,

~ n ;

setindentation (<>) - n ;
setRootisDecorated (<>) -

n False,

n n, n
n ;

setSortingEnaed (<>) -

n . True,

n .
n n ;

+
+

sortByColurnn (< > [, AscendingOrder]) - .


n AscendingOrder QtCore.Qt,
n n, DescendingOrder- ;
setWordWrap (<>) -

True,

n ;

selectedindexes () -

n (n- Qodelindex)

n n.

QTreeView :

expanded (const Qodelindex&) -

n .

n n (n QModelindex)
;

collapsed(const

QModelindex&)- n .

n n (n QModelindex)
.

24.

24.5.5.

545

QHeaderView QTaeView
QreeView.

QTaeView

horizontalHeader () verticalHeader (),


setHorizontalHeader (<QHeaderView>) setVerticalHeader ( <QHeaderView>).
QTreeView header (),
setHeader (<QHeaderView>). :

LJ

(QObject, QPaintDevice) - QWidget - QFrarne QAstractitemView

QAstractScrollArea

- QHeaderView

QHeaderView:

<>= QdrViw(<>[,

rnt=<>])

<> .

Horizontal Vertical QtCore.Qt.


QHeaderView
.

24.5. /)

QAstractitemView (.

; ):

count () -

+
+
+
+
+
+
+

len ();

setDefaultSectionSize (<>) - ;
defaultSectionSize () - ;
setMinimumSectionSize (<>) - ;
minimumSectionSize () - ~ ;
resizesection (<>, <>) - ;
sectionSize (<>) - ;
setResizeMode (<>) - .
QHeaderView:

Interactive- - ;
stretch- 1 -

. ,
;

Fixed- 2 - ;

ResizeToContents-

. ; , ;

setResizeMode (<>,

<>)

.+

setStretchLastSection (<>) -

True,

setCascadingSectionResizes (<>) -

rue,
;

18

1349

546

setSectionHidden (<>,

<>)

11.

rue, , , .

Fa1se ;

+ hideSect ion (<>) - ;


+ showsection (<>) - ;
+ isSectionHidden (<>) - True,
,

+
+
+

Fa1se-

sectionsHidden () Fa1se-

True,

hiddenSectioncount () - ;
setDefau1tAlignrnent

(<>)

setHigh1ightSections (<>) -

True,

setC1ickae (<>) -

True,

. , ;

setMovae (<>) -

True,

isMovae

() -

Fa1se-

movesection(<Oya>,

True,

<>)- .

swapSections (<!>, <2>) - .


;

visualindex(<1ogicalindex>)- (
) ( ) .
,

1ogicallndex (<visualindex>) -

-1;

) ( ) .
,

savestate () -

-1; .

QByteArray

restorestate ( <QByteArray>) -
QByteArray, savestate ().

QHeaderview ( ;
):

sectionPressed (int) -
. ;

sectionC1icked(int)-
.
;

24.

547

+ sectionDouleClicked (int) -

. n n ;

+ sectionoved(int,

int, int)- n n .

n n n ,
n- ; -
;

+ sectionResized (int,

int,

int) -

n n

. n n n
, n- , - .

24.6.

QitemSelectionodel , n n
n. l n
setSelectionodel(<QitemSelectionodel>)

QAstractitemView, n

n selectionodel

().

n, n

n n.
:

QObject -

QitemSelectionodel

QitemSelectionodel:
<>

QitemSelectionodel(<oe>)

<>= QitemSelectionodel(<Moe>,

<>)

QitemSelectionodel (n
; n n ):

t
t

hasSelection () - True, ,
false- n ;
isSelected(<Qodelindex>)-

True,

(n Qodelindex) , false- n ;

isRowSelected(<ec>,

<Qodelindex>)-

True,

false-

n ;

<> <Qodelindex> ,

isColumnSelected (<>, <Qodelindex>) -

<> <Qodelindex> ,

True,
false- n

rowintersectsSelection (<>,

<Qodelindex>)

True,

<> <Qodelindex> ,

false -

n ;

columnintersectsSelection(<ec>,

<Qodelindex>)-

True,

<> <Qodelindex>
,

false -

selectedindexes () -

n ;

n (n Qodelindex)

n n;

548

selectedRows ( [< >=]) -

1/.

n (n

QModelindex) . nn n
, n;

selectedColnns ( [<

>=]) -

n (n

QModelindex) . nn
n , n;

selection () - n QitemSelection;
select (<Qodelindex>,

<>)

. n (
n

1) QitemSelectionodel:

NoUpdate- ;

Clear-

Select-

Deselect

Toggle-

;
;

- ;
, , , -

current -

Rows- , ;

Colnns- , ;

Selectcurrent- Select

Current;

ToggleCurrent- Toggle

Current;

ClearAndSelect -

Clear

Select.

select(const

Qodelindex&,

QitemSelectionodel::SelectionFlags);

select (<QitemSelection>, <>) - ..

select(const
Qiteffiselection&,
QitemSelectionodel::
SelectionFlags);

setCurrentindex (<QModelindex>,

Qodelindex&,

<>) -

setCurrentindex (const

QitemSelectionodel::SelectionFlags);

currentindex () -

(n

Qodelindex) -

clearselection () - . .

QitemSelectionodel :

currentChanged(const QModelindex&, const QModelindex&)- n


. n n .
n , n

currentRowChanged(const

QModelindex&,

const QModelindex&)- ,

n .
n n n , n
;

549

24.

currentColnnChanged(const Qodelindex&,

const

Qodelindex&)- ,

n 1. n

na-

paeip n n , n-
;

t selectionChanged(const QitemSelection&, const QitemSelection&)-

24.7.

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

QSortFilterProxyModel
QSortFilterProxyModel

n.

QObject -

QAstractitemodel

QAstractProxyModel QSortFilterProxyModel

QSortFilterProxyodel:
<>= QSortFilterProxyModel([parent=<Poe>])

QSortFilterProxyodel QAstractProxyodel

(n ; n n ):

+
+

setSourceModel (<>)-
sourceModel ()

- .

QSortFilterProxyModel

n t n

(n ; n
n ):

sort (<

>[,

order=AscendingOrder]) - n .
AscendingOrder QtCore.Qt,
n, DescendingOrder- . n

n
n n

< > -1, n n


.

,
setSortingEnaed

setSortRole (<>)

()

- (. .

24.3),

. n

setSortCaseSensitivity(<Pe>)-

caseinsensitive
,

DisplayRole;

QtCore.Qt, n
Casesensitive- ;

setSortLocaleAware (<>)

True

- n rue, n

setFilterFixedString(<pae>)- nn ,

n ,

nn

550

11.

setFilterFixedString(const QString&);

setFilterRegExp () -

. ,

. :

setFilterRegExp(<QRegExp>)
setFilterRegExp(<Cpoa >)

QRegExp,

setFilterRegExp (const QString&);

setFilterWildcard (<>) -

, :

? - ;

*-

[ J -

;
.

.
, .

setFilterWildcard (const QString&) ,;

setFilterKeyColumn(<ec>)- ,

. -1,
.
;

setFilterRole(<Po>)- (. .

24.3),

. DisplayRole;

setFilterCaseSensitivity(<Pe>)-

caseinsensitive QtCore.Qt,
, Casesensitive- .;

setDynarnicSortFilter (<>) - True,



.

25

, ,

. ( ,
, , )

paintEvent () ( . .

21.8.3).

repaint () update ()
QWidget. paintEvent ()
QPainter.

QPainter ,
n, QPaintDevice.
QWidget QPaintDevice. QWidget
,

QPaintDevice QPicture, QPixmap, Qimage, QPrinter


. QPicture ,
- . QPixmap Qimage
, QPrinter
DF-. .

PyQt SVG-, , ,

OpenGL,

. .
.

25.1.

,
, (
, , , ). , ,

(, ).

25.1.1.

QColor.

QColor QtGui

HSL.

QColor:

<>

= QColor()

<>= Qlr(<>,

<>,

<>[,

alpha=255])

RGB,

HSV

552
<>

11.

QColor(<Cpoa>)

<>

Qlr(<>)

<>

Qlr(<>)

<>

QColor(<QColor>)

.
n isValid (). True,
,

False -

n .

n ,

RGB.

255.

n alpha n n .
n ,

255- n n.

red

QtGui.QColor(255,

0)

"#RGB", "#RRGGBB",

"#RRRGGGBBB", "#RRRRGGGGBBBB", " " "transparent" ( n


). :

red = QtGui. QColor ( "# fOO" )


darkBlue = QtGui.QColor("#OOOOBO")
whi te = QtGui. QColor ( "whi te")
n

colorNarnes (). n n
isValidColor (<>). True,
, False n . :
print(QtGui.QColor.colorNarnes()) # ['aliceue', 'antiquewhite', ... ]
print(QtGui.QColor.isValidColor("lightcyan")) # True

QtCore.Qt: white,
red, darkRed, green, darkGreen, u, darkBlue, cyan, darkCyan, magenta, darkagenta,
yellow, darkYellow, gray, darkGray, lightGray, colorO, colorl transparent (n
). colorO (n ) colorl (n ) n

k,

. :
k

QtCore.Qt.ack

n ,

n.
n

RGB (Red, Green, Blue;

, ,

) n :

setNarnedColor (<>) "#RGB",


"#RRGGBB", "#RRRGGGBBB", "#RRRRGGGGBBBB", " " "transparent" (
n );

+
+

name () - n "#RRGGBB";
setRgb(<!<:pac>,

<>,

<>[,

alpha=255])-

RGB.

255. n alpha n n
. n , 255- n
ri;

25.

553

setRed (<>), setGreen (<>), setBlue (<>) setAlpha (<alpha>) -

t
t

255;

setRgb (<>) setRgba (<>) - ;


fromRgb(<i<:pac>, <>, <>[, alpha=255])-
QCo1or . 255.
. :

white = QtGuioQColor.fromRgb(255, 255, 255, 255)

fromRgb (<>) fromRgba (<>) - QColor


, , .
. :

white = QtGuioQColor.fromRgba(4294967295)

t
t

getRgb () - (<>, <


>, <>, <alpha>);
red (), green (), u () alpha () -
;

t
t

rgb () rgba () - ;
setRgbF(<pac>,

<>,

<>[,

alpha=loO])- ,

RGB.
10 . alpha
. , 10 -
;

setRedF (<>), setGreenF (<>), setBlueF (<>)

setAlphaF (<alpha>) -

10 ;

fromRgbF(<pac>,

<>, <>[, alpha=1o0])-


QColor .
. 10 . . :

whiteo= QtGuioQColorofromRgbF(1oO,

getRgbF () >,

10,

10,

10)

(<>,

<>,

<

<alpha>);

redF (), greenF (), ueF () alphaF () -

lighter ( [factor=l50]) - 100,


, 100- ;

darker( [factor=200])- 100, , 100- .

(Cyan, Magenta, Yel\ow,

, , , "" ()) :

stmk(<>,

<>,

<>,

<>[,

alpha=255])-

.
255. alpha

554

11.

. , 255-
;

fromCmyk

(<>,

<>,

<>,

<>

[,

a1pha=255] ) -

QCo1or .
255. . :

white = QtGui.QCo1or.fromCmyk(0,

+
+

255)

getCmyk () :>,

<>,

<>,

(<>,

<

<a1pha>);

(), mageta (), yellow (), lack () a1pha () -

setCmykF(<oyo>,

<>,

<>,

<>[,

a1pha=1.0])-

.
. 1. . a1pha
. . , 1. -
;

fromCmykF(<oyo>,

<>,

<>,

<>[,

a1pha=1.0])-

QCo1or .
. 1. . . :

white = QtGui.QCo1or.fromCmykF(O.O, 0.0, 0.0, 0.0, 1.0)

getCmykF () >,

(<>,

<>,

<>,

<

<a1pha>);

cyanF (), magentaF (), yellowF (), lackF () a1phaF () -

HSV (Hue, Saturation, Value;

, ()) :

setHsv (<>,

<>,

<>

359,

white =

[,

a1pha=255 J ) -

255;

frmsv(<>,

HSV.

<>, <>[, a1pha=255])-


QCo1or . . :

QtGui.QCo1or.fromsv(O,

255, 255)

getHsv () -

(<>,

>,

<>,

<

<a1pha>);

hsvHue (), hsvSaturation (), va1ue ()

a1pha () -

setHsvF (<>,

<>,

HSV.

<> [,

a1pha=1. ] ) -

1.0;

fromsvF(<Oeo>,

<>,

<>[,

a1pha=1.0])-

QCo1or .
. 1. . . :

white =

QtGui.QCo1or.fromsvF(O.O,

0.0, 1.0, 1.0)

25.


(<>,

getHsvF () >,

555

<>,

<

<alpha>);

hsvHueF (), hsvSaturationF (), valueF ()

alphaF () -

HSL (Hue, Saturation, Lightness)

HSV

.
.

spec () -

,
()

QColor: Invalid (), Rgb (1), Hsv (2), Cmyk

Hsl ( 4);

converto (<n >)

. !'

spec ().

. :

whiteHSV = QtGui.QColor.fromsv('O, , 255)


whiteRGB = whiteHSV.convertTo(QtGui.QColor.Rgb)

toHsv ()

converto

toHsl (),

()

whiteHSV = QtGui.QColor.fromsv(O,
whiteRGB = whiteHSV.toRgb()

25.1.2.

QPen

QPen.

toRgb (), toCmyk (),

-. :

QtGui

255)

, . :
<>

<>
<>

<>

<>

= QPen()
= QPen(<QColor>)
= Qn(<>)
= QPen(<QBrush>, <>[, style=SolidLine] [, cap=SquareCap] [,
join=BevelJoin])
= QPen(<QPen>)

QColor.

QtCore. Qt:

t
t
t
t

NoPen-

DashDotLine- 4 -

DashDotDotLine- 5 -

- ;

SolidLine- 1 -
DashLine- 2 DotLine -

t CustomDashLine-

, . ..;
, . .

- .

556

11.

.1

QBrush

QColor.

style.

FlatCap-

QtCore. Qt:

- .

SquareCap- 16-

RoundCap- 32-

join

+
+
+
+

MiterJoin-

QtCore .Qt:

- ;
- ;

BevelJoin- 64

RoundJoin- 128-

SvgMiterJoin- 256.

QPen

( ;

):

+
+
+
+

setColor (<QColor>) -

setBrush (<QBrush>) -

setWidth (<int>)

setWidthF (<float>)

setStyle (<>)-

(.

setCapStyle (<>)

- (.

QPen)j

setJoinStyle (<>) -
join , QPen).

25.1.3.

style

QPen);

- ;

QBrush.

(.

QBrush QtGui ,
. :
<>
<>

QBrush ( )
QBrush(<QColor>[, style=SolidPattern])

<>

QBrush(<C

<>

QBrush(<QGradient>)
QBrush(<QColor>, <QPixmap>)
QBrush(<QPixmap>)
QBrush(<Qimage>)
QBrush(<QBrush>)

<>

~>
<>

<>

>)

25.

557

<QColor> . n n QColor

QtCore. Qt,

n < >

style QtCore .Qt,

NoBrush,

DensePattern,

n, k.

n,

SolidPattern,

Dense4Pattern, Dense5Pattern,

DenselPattern,

Dense2Pattern,

DensePattern,

Dense7Pattern, CrossPattern
. n n n (solidPattern)
(n, CrossPattern ).
<QGradient> n .
n QLinearGradient ( ), QConicalGradient
( ) QRadialGradient. ( ). n
.

<QPixrnap> <Qirnage> n

QBrush (n ; n
n ):

+
+
+

setColor ( <QColor>) - ;
setStyle (<>) - (. n style
QBrush);
setTexture (<QPixrnap>) - . n
QPixrnap QBitrnap;

setTextureimage (<Qirnage>)- .

25.1.4.

QLine.

QLine QtCore n . :

QLine()
QLine(<QPoint>, <QPoint>)
<>= QLine(<Xl>, <Yl>, <2>, <2>)
<> = QLine(<QLine>)

<>=

<>=

.
n

QPoint

n.
.

QLine .
,

QLineF.

QLine (n ; n

n ):

isNull () - True,
False- n ;

setPoints (<QPoint>,

<QPoint>) QPoint;

558

setLine (<Xl>,

<Yl>,

<2>,

<2>)

/1.

+
+
+
+
+

setPl (<QPoint>)

- ;

setP2 (<QPoint>)

- ;

pl () - ( QPoint) ;
2

() - ( QP0int) ;

xl (), yl (),

()

() -

+
+

dx () -

dy () -

25.1.5.

QPo/ygon.

QPo~ygon

QtGui .

= QPolygon()
= QPolygon(<Cco n QPoint>)
<> = QPolygon(<Cco >)
<>= QPolygon(<QRect>[, closed=False])
<> = Qlgn(< >)
<> = QPolygon(<QPolygon>)
<>
<>

polygon = QtGui.QPolygon()
polygon << QtCore.QPoint(20, 50) << QtCore.QPoint(280, 50)
polygon << QtCore.QPoint(l50, 280)

QPoint,

. :

polygon = QtGui.QPolygon([QtCore.QPoint(20, 50), QtCore.QPoint(280, 50),


QtCore ."QPoint ( 150, 280) ] )
:

polygon = QtGui.QPolygon([20,50, 280,50, 150,280])


True-

QRect.
closed False, ,
.

n , n
:

polygon = QtGui.QPolygon()
polygon[O] = QtCore.QPoint(20, 50)
polygon[l] = QtCore.QPoint(280, 50)
polygon[2] = QtCore.QPoint(l50, 280)
.

25.

559

QPolygon

n .

, n

QPolygonF.

QPolygon ( ;

):

t setPoints () -

. :
setPoints(<Cnco

>)

setPoints(<Xl>, <Yl>[, ... , <Xn>, <Yn>])


:

polygon = QtGui.QPolygon()
polygon.setPoints([20,50, 280,50, 150,280])

t prepend (<QPoint>) -
t append (<QPoint>) -

insert

(<>,

t setPoint ()

<QPoint>)

;
.

+=;

- ;

- . :

setPoint(<ec>,

<QPoint>)

setPoint(<ec>,

<>,

<>)

~ :

polygon = QtGui.QPolygon()
polygon.setPoint(O, QtCore.QPoint(20, 50))
polygon.setPoint(l, 280, 50)
polygon[2] = QtCore.QPoint(l50, 280)

point (<>) -

QPoint

() ,

.
. :

polygon = QtGui.QPolygon([20,50, 280,50, 150,280])


print(polygon.point(O)) # PyQt4.QtCore.QPoint(20, 50)
print(polygon[l])
# PyQt4.QtCore.QPoint(280, 50)

t remove (<> [,

<> J)

<>. , .

clear ()

t size ()

del ;

- ;

count ( [ <QPoint> J ) -

count ()

t isEmpty () -

True,

len ();

False-

boundingRect ()

QRect

, .

560

25.1.6.

QFont.

11.

QFont QtGui .
:

<>=

QFont()

<>= QFnt(< >[,

pointSize=-1] [, weight=-1]
[, italic=False])

<>=

QFont(<QFont>)

, !i
.

setFont ()

QApplication.

.
pointSize . weight
: 99 Light

(75)

Black

(25), Normal (50), DemiBold (63), Bold

QFont. italic True,

(87)

.
.
QFont ( ;
):

+
+
+
+
+

setFamily(<Haae >) - ;

family () - ;
setPointSize (<int>) setPointSizeF(<float>)- ;
pointSize () -
-1, ;
pointSizeF () -

-1, ;

+
+

setPixelSize (<int>) - ;
pixelSize () -

-1,

setWeight (<>) - : 99
Light (25), Normal (50), DemiBo1d (63), Bold (75) Black (87)
QFont;

+
+

weight () -

setBold (<>) -

True,

Bold, False-
Normal;

bold () -

rue,

Nonnal, False- ;

setrtalic(<a>) _;_ True,


,

italic () ;

False-

rue, , Fa1se-

25.

561

setUnderline (<>) - n rue,


False- n;

n,

+ underline ()

True, n, False-

n ;

setOverline (<>) - n True,


. ;

+ overline ()
False-

True, ,

n ;

setStrikeOut (<>)- n True,


n;

strikeOut () -

True, n , .False-

n .

n n . n families ()

QFontDatabase. n . :
print(QtGui.QFontDatabase() .families())
n n n , n

styles

(< >)

QFontDatabase:

print (QtGui .QFontDatabase () . styles ("Tahoma"))


# [ 'Normal', 1 Italic 1 , 1 Bold 1 , 1 Bold Italic 1 ]

smoothSizes

(< >,

<>)

n~

QFontDatabase:

print (QtGui .QFontDatabase (). smoothSizes ( "Tahoma", "Normal"))


# [6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72]
n
. , , n .
n

width (<> [, length=-1 J ) -

QFontMetrics:

<> n

, .

length

+
+

height () -

boundingRect (<>) - n QRect


n ,. n .

n :

font = QtGui. QFont ( "Tahoma", 1 )


fm = QtGui.QFontMetrics(font)
pr int ( fm. width ("") )
# 67
print(fm.height())
# 25
print(fm.boundingRect("Cpoa")) # PyQt4.QtCore.QRect(O, -21, 65, 25)
, , width () QRect. width (),
.

QFontMetrics n .
QFontMetricsF.

562

25.2.

11.

QPainter

QPainter

QPaintDevice

QPaintDevice.
QWidget, QPicture, QPixmap, Qirnage, QPrinter

. , ,
. :
<>
<>=

QPainter()
QPainter(<QPaintDevice>)

, .
,

begin (<QPaintDevice>) 'f ,


QPaintDevice. True,
, False- .
,

end ().

, :

def paintEvent(self, ):
painter = QtGui.QPainter()
painter.begin(self)
# n
painter. end ()

QPaintDevice,

QPainter .
paintEvent (), end () .
:

def paintEvent(self, ):
painter = QtGui:QPainter(self)
#


rue, ,

25.2.1.

E'alse-

isActive ().

, ,
.

set Pen ( <QPen>)


setPen(<QColor>)
stn(<

>)

setBrush(<QBrush>)
setBrush(<C

>)

setpen () QPainter. :

setBrush () .

563

25.

,
. ,
.
, , , .

, QPainter (
;

QPainter):

+ drawPoint ()

- . :

drawPoint(<X>, <>)
drawPoint(<QPoint>)
drawPoint(<QPointF>)

+ drawPoints ()

- . :

drawPoints(<QPoint 1>[, ... , <QPoint N>])


drawPoints(<QPointF 1>[, ... , <QPointF N>])
drawPoints(<QPo1ygon>)
drawPoints(<QPo1ygonF>)

drawLine () - . :
drawLine(<QLine>)
drawLine(<QLineF>)
drawLine(<QPoint>, <QPoint>)
drawLine(<QPointF>, <QPointF>)
drawLine(<X1>, <1>, <2>, <2>)

drawLines () -

. :

drawLines(<QLine 1>[, ... , <QLine N>])


drawLines(<QLineF 1>[, ... , <QLineF N>J)
drawLines(<Cco
drawLines(<Cco

QLine>)
QLineF>)

drawLines(<QPoint 1>[, ... , <QPoint N>])


drawLines(<QPointF 1>[, ... , <QPointF N>])
drawLines(<Cco n QPoint>)
drawLines(<Cco QPointF>)

drawPo1yline () -

, .

. :

drawPo1y1ine(<QPoint 1>[, ... , <QPoint N>])


drawPo1yline (<QPo"intF 1> [, ... , <QPointF N>])
drawPo1y1ine(<QPo1ygon>)
drawPo1y1ine(<QPo1ygonF>)

drawRect () - . ,
NoPen, -
Norush. :

drawRect(<X>, <>,
drawRect(<QRect>)
drawRect(<QRectF>)

<>,

<>)

564
t

fillRect () - . :
fi11Rect(<X>, <>, <>, <>, <QBrush
fi11Rect(<QRect>, <QBrush QCo1or>)
fi11Rect(<QRectF>, <QBrush QCo1or>)

11.

drawRoundedRect () -

QCo1or>)

. :

drawRoundRect(<X>, <>, <>, <>


[ , xRound=2 5] [ , yRound=2 5] )
drawRoundRect(<QRect>[, xRound=25] [, yRound=25])
drawRoundRect(<QRectF>[, xRound=25] [, yRound=25])

drawPo1ygon () - . i :
drawPo1ygon(<QPoint 1>[, ... , <QPoint N>])
drawPo1ygon(<QPointF 1>[, ... , <QPointF N>])
drawPo1ygon(<QPo1ygon>[, fi11Ru1e=OddEvenFi11])
drawPo1ygon(<QPo1ygonF>[, fi11Ru1e=OddEvenFi11])

drawEllipse ()

- . :

drawE11ipse(<X>, <>, <>, <>)


drawEllipse(<QRect>)
drawE11ipse(<QRectF>)
drawE11ipse(<QPoint>, <int rX>, <int rY>)
drawE11ipse(<QPointF>, <f1oat rX>, <f1oat rY>)
,
.
,

drawArc ()

rx-

rY-

- . :

drawArc(<X>,

<>,

<>,

<>,

< >,

<>)

drawArc(<QRect>, < >, <>)


drawArc(<QRectF>, < >, <>)
,

16 * 360.

1/16

,
;

drawChord () drawArc ().

drawChord ()

. :

drawChord(<X>,

<>,

<>,

<>,

<~ >,

<>)

drawChord(<QRect>,
drawChord(<QRectF>,

drawPie () -

< >,

< >,

<>)

<>)

drawPie ()

. :

drawPie(<X>,

<>,

<>)

<>,

<>,

<~ >,

drawArc (),

25.

565

drawPie(<QRect>, < >, <>)


drawPie(<QRectF>, < >, <>)
(, n) "

". , . setRenderHint ()

Antialiasing.

painter.setRenderHint(QtGui.QPainter.Antialiasing)

25.2.2.

drawext
drawext(<X>,

<>,

<>)

drawext(<QPoint>,

<>)

drawext(<QPointF>,

drawext(<X>,

<>,

drawext(<QRect>,

() QPainter. :

<>)

<!II>,
<>,

<>,

<>,

<>)

<>)

drawext(<QRectF>,

<>,

drawext(<QRectF>,

<>[,

<>)

option=QextOption()])

, .
.

extDontClip.

QRect (QRectF )

, . <>
1 AlignLeft, .AlignRight, AlignHCenter, AlignTop,
AlignBottom, AlignVCenter AlignCenter QtCore.Qt,
, :

TextDontClip- ;

TextSingleLine-
;

TextWordWrap _:_____ ,
;

TextWrapAnywhere- ;

TextShowMnemonic- ,

&, .

&, ;

TextHideMnemonic- , TextShownemonic, ;

TextExpandTabs- .

drawext ()
,

QTextOption. ,
( , .).

, ,

boundingRect ().

boundingRect(<X>, <>, <>, <>,


boundingRect(<QRect>, <>, <>)

<>,

<>)

566
boundingRect(<QRectF>,
boundingRect(<QRectF>,

<>,

<>)

<>[,

option=QextOption()J)

cundingRect
-

/1.

()

QRect,

QRectF.

"".
,

setRenderHint () TextAntialiasing.

painter.setRenderHint(QtGui.QPainter.TextAntialiasing)

25.2.3.

drawPixrnap () drawimage ()
QPainter. drawPixrnap () ,
QPixrnap. drawPixrnap ():

drawPixrnap(<X>, <>, <QPixrnap>)


drawPixmap(<QPoint>, <QPixrnap>)
drawPixrnap(<QPointF>, <QPixrnap>)
drawPixmap(<X>, <>, <>, <>, <QPixrnap>)
drawPixrnap(<QRect>, <QPixrnap>)
drawPixmap(<Xl>, <Yl>, <QPixrnap>, <2>, <2>, <2>,
drawPixrnap(<QPoint>, <QPixrnap>, <QRect>)
drawPixmap(<QPointF>, <QPixrnap>, <QRectF>)
drawPixmap(<Xl>, <Yl>, <l>, <l>, <QPixrnap>,
<2>,

<2>,

<2>,

<2>)

<2>)

drawPixrnap(<QRect>, <QPixrnap>, <QRect>)


drawPixmap(<QRectF>, <QPixrnap>, <QRectF>)
,
,

QPixrnap.

pixrnap = QtGui .QPixrnap ( "foto. jpg")


3, pixrnap)

painter.drawPixrnap(,


. ,

.
.

, ,

QRect

QPixrnap,

QRectF.

QPixrnap, ~
QRect QRectF.

, .
.

25.

567

drawimage () ,
Qimage. Qimage QPixmap.
n flags.
drawimage ():

drawimage(<QPoint>, <Qimage>)
drawimage(<QPointF>, <Qimage>)
drawimage(<QRect>, <Qimage>)
"ctrawimage(<QRectF>, <Qimage>)
drawimage(<X1>, <1>, <Qimage>[, sx=O] [, sy=O] [, sw=-1] [, sh=-1]
[, flags=AutoColor])
drawimage(<QPoint>, <Qimage>, <QRect>[, flags=AutoColor])
drawimage(<QPointF>, <Qimage>, <QRectF>[, flags=AutoColor])
drawimage(<QRect>, <Qimage>, <QRect>[, flags=AutoColor])
drawimage(<QRectF>, <Qimage>, <QRectF>[, flags=AutoColor])
( 111 )
, ,

Qimage.

img = QtGui.Qimage ("foto.jpg")


3, img)

painter.drawimage(,


. ,
.
.

, ,
.

QRect

Qimage,

QRectF.

Qimage,

QRect

QRectF.

,
.
.

25.2.4.

(viewport; )
(window).

.
. .

setViewport (),
viewport ().
setWinctow (),

window ().

QPainter:

568

11.

trans1ate () -

. ,

- . :

trans1ate(<X>, <>)
trans1ate(<QPoint>)
trans1ate(<QPointF>)

rotate

(<>) ~

( ).
, - ;

sca1e (< >, < >) -

. , .
, - ;

shear (< >,

< >) -

. ,

painter. save ()
painter.restore()

#
#
#

save (),

restore ():

, . 1:1 .
,

QMatrix, setMatrix (). :

matrix = QtGui.QaLrix()
matrix.trans1ate(105, 105)
matrix.rotate(45.0)
painter.setMatrix(matrix)
painter.fi11Rect(-25, -25, 50, 50, QtCore.Qt.green)

25.2.5.

QPicture

QPaintDevice - QPicture
:
<>
<>=

QPicture([formatVersion=-1])
QPicture(<QPicture>)

formatVersion

. , ,

PyQt.

25.

569

save (< >) - . True,


False- ;

load (< > 1 - .


True, , False- .

drawPicture ( 1

QPainter.

drawPicture(<X>, <>, <QPicture>)


drawPicture(<QPoint>, <QPicture>)
drawPicture(<QPointF>, <QPicture>)
:

painter = QtGui.QPainter()
pic = QtGui.QPicture()
painter.begin(pic)
# -
painter. end ()
pic.save("pic.dat")
:

def paintEvent(self, ):
painter = QtGui.QPainter(self)
pic = QtGui.QPicture()
pic.load("pic.dat")
painter.drawPicture(O, , pic)

25.3.

PyQt

- (

QPixmap QBitmap) -
Qimage) . , ,
supportedimageFormats() QimageReader.
QByteArray.
(

for i in QtGui.QimageReader.supportedimageFormats():
print (str (i, "ascii") .upper(), end=" ")
:

GIF ICO JPEG JPG

NG

PGM PNG

SVG SVGZ TIF TIFF

, ,

supportedimageFormats ( 1 QimageWri ter.


QByteArray. : :

for i in QtGui.QimageWriter.supportedimageFormats():
print(str(i, "ascii") .upper(), end=" ")
:

ICO JPEG JPG PNG

TIF TIFF

570

11.

, GIF,
, . . , n
, .

25.3.1.

QPixmap

QPixmap n - n
. , ~;~

, n
n . :

QPaintDevice - QPixmap

QPixmap QPaintDevice, n
drawPixmap ()

QPainter (. . 25.2.3).
:
<>

.<>
<>

= QPixmap ()
= Qim\<>,
= QPixmap(<QSize>)

<>= Qim(<
<>

<>)

>[,

format=None] [, flags=AutoColor])

QPixmap(<Q~ixmap>)

.
. ,
.
, n n .
QPixmap ( ; n
):

True, , False- n

isNull () -

load (< > [, format=None] [, flags=AutoColor]) -


. n .
. n
, n . n flags n
. rue, n
,

False -

loadFromData ( <QBYteArray> [,

format=None] [,

f lags=AutoColor] ) -

n QByteArray. n ,
bytes. rue,
,

False

- ;

save (< >[, format=None] [, quality=-1]) - .


..
n . n ,
n . n

quality .
100. rue, ,
False - ;

25.

571

+ convertFromimage (<Qimage> [,

flags=AutoColor])
Qimage QPixmap. rue,
, False- ;

+ fromimage (<Qimage> [,

flags=AutoColor]) -

Qimage

QPixmap . ;

+ toimage () -

QPixmap Qimage

. :

fill () -

fill([color=white])
fill(<QWidget>, <>, <>)
fill(<QWidget>, <QPoint>)

+ width () - ;
+ height () - ;
+ size () - QSize ;
+ rect () - QRect
, ;

+
+
+
+
+

depth () -

isQBitmap () rue, ,
False - ;
setMask ( <QBi tmap>) - ;
mask () -

QBi tmap ;

() -

QPixmap .

rect , . :

copy([rect=QRect()])
(<>,

<>,

scaled () -

<>,

<>)

QPixmap.

. :
sld(<>,

<>[,

aspectRatioMode=IgnoreAspectRatio] [,

transformode=FastTransformation])

scaled(<QSize>[, aspectRatioMode=IgnoreAspectRatio] [,
transformode=FastTransformation])

aspectRatioMode

QtCore.Qt:

IgnoreAspectRatio- -
;

KeepAspectRatio- 1 -
;

KeepAspectRatioByExpanding- 2 -

transformode

QtCore.Qt:

572

11.

- ;

FastTransformation-

SmoothTransformation- 1 -

sca1edToWidth (<> [,

mode=FastTransformation]) -

QPixmap.

. . mode
transfornode

sca1ed ();

sca1edToHeight (<> [,

mode=Fastransformatit>n]) -

QPixmap.
u. . mode
transfornode

sca1ed ();

transformed ( <QMatrix> [,

mode=Fastransformation]) -

(, ) QPixmap.
.

QMatrix. mode transfornode sca1ed ();

grabWindow(<winid>[,

=]

[,

=]

[,

width=-1] [,

height=-1])-

( ). QPixmap.
winid ()
QWidget. .
, .
. .

QtGui.QPixmap.grabWinoJ.ow(window.winid()) .save("window.png",
"PNG")
:

desktop = QtGui.QApp1ication.desktop()
QtGui.QPixmap.grabWindow(desktop.screen() .winid()
) .save ("screen.png", "PNG")

grabWidget () - .
QPixmap. . :
grabWidget(<QWidget>[, =] [,
grabWidget(<QWidget>, <QRect>)

25.3.2.

=]

[, width=-1] [, height=-1])

QBitmap

QBitmap ,
, - . QBitmap
. :

QPaintDevice - QPixmap - QBitmap


QBitmap QPaintDevice,
. co1or0 ( )

co1or1 ( ) QtCore .Qt.


drawPixmap () QPainter (. . 25.2.3).

25.

573

:
<>

<>
<>

= QBitmap()
= QBitmap(<IIlpa>,
= QBitmap (<QSize>)

<>= QBitmap(<y

<>)

QBitmap(<QPi~~ap>)

<>=

QBitmap(<QBitmap>)

QBitmap

format=None])

>[,

<>

QPixmap

( ; ~
):

fromimage (<Qimage> [, flags=AutoColor]) - Qimage


QBitmap . ;

+ transformed(<QMatrix>)-

(,

QBitmap.

Qatrix;

clear () - colorO.

25.3.3.

Qlmage

Qimage -
Qimage
QPixmap. :

QPaintDevice - Qimage

Qimage

QPaintDevice,

. ,

Format_ARG32_Premultiplied.

drawimage ()

QPainter (. . 25.2.3).
:
<>=

Qimage()

<>= Qimg(<>,

<>

<>,

<>)

<>)

Qimage(<QSize>,

<>

Qimage(<y

<>

Qimage(<Qimage>)

>[,

<n >])

.
. ,
.

. (,

"PNG"). , !-l.
.
<>

; ):

Format _ Invalid- - ;

Format _Mono- 1 -

1 ;

Qimage

574

+
+
+
+
+

Format_Indexed8- 3 -
Format_RG32- 4 -

RGB

Format_ARGB32- 5 -

1 ;

Format _ MonoLSB- 2 -

11.

8 ;

-,

RGB

-,

Fo~t _ ARGB32 _Premul tiplied- -

RGB

32 ;
32

-,

32

.
Qimage ( ;
):

True, , False-

isNull () -

ld(<

>[,

format=None])- .

.
(, "PNG"). ,
. rue,
,

False-

loadFromData ( ~QByteArray> [, format=None J )


QByteArray. , bytes.
(, "PNG").
rue, ~ , False-

fromData ( <QByteArray> [, format=None J ) -


QByteArray. , bytes.
(, "PNG").
Qimage. ;

save (< > [, fo.rmat=None] [, quality=-1]) - .


.
. ,

quality .
100. True, ,
False- ;

fill (<>) -

rgb () rgba () QColor. :

img. fill (QtGui .QCo1or ( "#ffOOOO") .rgb ())

+
+
+
+

width () height () -

;
;

size () - QSize ;
rect () - r QRect
, ;

+
+

depth () -

format () - (. <>
Qimage);

25.

setPixel ()

575

- . :

setPixel(<X>, <>,
setPixel(<QPoint>,

< >)
< >)

< > 8-
, 32-- .

rgb ()

rgba ()

QColor;

pixel () -

QColor,

. :

pixel(<X>, <>)
pixel(<QPoint>)

convertToForrnat ()

<>

(.

Qimage) Qimage.

. :

flags=AutoColor])

convertToForrnat(<opa>[,
convertToForrnat(<opa>,

< >[,

flags=AutoColor])

()

- Qimage ~.
rect , . :

copy([rect=QRect()])
(<>,

<>,

scaled () -

<>,

<>)

Qimage.

. :
sld(<>,

<>[,

aspectRatioMode=IgnoreAspectRatio] [,

transformode=FastTransforrnation])

scaled(<QSize>[, aspectRatioMode=IgnoreAspectRatio] [,
transformode=FastTransforrnation])

aspectRatioMode

QtCore. Qt:

IgnoreAspectRatio' ;

KeepAspectRatio- 1 -

KeepAspectRatioByExpanding- 2 -

.
transformode

QtCore.Qt:

Fastransforrnation- - ;

SmoothTransforrnation- 1 -

scaledToWidth (<> [,

mode=FastTransforrnation]) -
Qimage. -

576

11.

. .

mode

scq.led ();

transformode

scaledToHeight (<> [, mode=FastTransformation] ) -


n Qimage. nn
. . mode n
transformode scaled ();

transformed (<QMatrix> [,

mode=FastTransformation]) -

(n, n) n
.

mode

Qatrix.

invertPixels ( [mode=InvertRgb])

Inv~rtRgba

Qimage.

n transformode

scaled ();

- n .

mode

InvertRgb

Qimage;

mirrored ( [horizontal=False] [,

vertical=rue])

. n

Qimage.

25.3.4.

Qlcpn

n , .

Qicon

Qicon

QPaintDevice,

n n . :
<>
<>
<>

<>

= Qicon ()
= Qin(< >)
= Qicon(<QPixmap>)
= Qicon(<Qicon>)

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

QPixmap,

Qicon

n .

(n ; n

n ):

isNull () -

rue, ,

False-

addFile(<y

>[,

size=QSize()][, mode=Normal][,

stt=ff])-

, .
, n.

( n

QSize).

size

mode

n n n, .

Selected.

state

Qicon: Normal, Disaed, Acti ve


Off on Qicon;

addPixmap (<QPixmap> [, mode=Normal] [, state=Off]) -

. n

availaeSizes

QPixmap;

( [mode=Normal] [, state=Off]) -
QSize) ;

25.

actualSize(<QSize>[,

577

mode=Nonal] [,

state=Off])-

( QSize) n , .

, , :

pixmap () -

( QPixmap),

, . :
im(<>,

<>[, mode=Normal] [, state=Off])


pixmap(<QSize>[, mode=Normal] [, state=Off])

.
:

ico = window.style() .standardicon(QtGui.QStyle.SP_MessageBoxCritical)


QStyle

( :/Python 2/L i/ s ite-packages/PyQt4/doc/htm 1/qsty le. htm 1#S tandard Pix map-en um).

-26

(, , .)
(, ,
.).

"/",
.
. :

QGraphicsScene- ,
. ;

QGraphicsView- .
;

QGraphicsitern- .
~
,

QGraphicsRect Itern (), QGraphicsEllipseitem (

) .

26.1.

QGraphicsScene.

QGraphicsscene ,

. .
:

QObject - QGraphicsScene
:
<>=
<>=
<>=

QGraphicsScene([parent=None])
QGraphicsScene(<X>, <>, <>, <>[, parent=None])
QGraphicsScene(<QRectF>[, parent=None])

, .

_
.

QRectF.

parent

26.

26.1.1.

579

c;GraphicsScene:

setSceneRect () - . :
setSceneRect(<X>,

<>,

<>,

<>)

setSceneRect(<QRectF>)

+
+

sceneRect () - QRectF ;
width () height () -
;

itemsBoundingRect ()- QRectF


, , ;

setBackg roundrush ( <QBrush>) -

). ,

drawBackground ()
;

setForegroundrush(<QBrush>)- (
). ,
drawForeground () :
;

+
+

setFont (<QFont>) - ;
setltemindexethod(<Pe>)- .
QGraphicsScene:

spTreeindex- -
. ,
;

Nolndex- - 1 - . ' ~
;

setBspTreeDepth ( <rt>) -

BspTreeiridex. , ,
;

bspTreeDepth ()

26.1.2.

BspTreelndex.

QGraphicsScene:

additem(<QGraphicsitem>) - .
, QGraphicsrtem, ,

c;GraphicsEllipseitem ();

adc!Line () - , (
QGraphicsLineitem).

580

/1.

addLine(<Xl>, <Yl>, <2>, <2>[, pen=QPen()])


addLine(<QLineF>[, pen=QPen()])

addRect () -

( QGraphicsRectitem). :

addRect(<X>, <>, <>, <>[,


pen=QPen()] [, brush=QBrush()])
addRect(<QRectF>[,. pen=QPen()] [, brush=QBrush()])

addPolygon () - ,
( QGraphicsPolygonrtem). :
addPolygon(<QPolygonF>[, pen=QPen()] [, brush=QBrush()])

addEllipse () -

( QGraphicsEllipsertem). :

addEllipse(<X>, <>, <>, <>[,


pen=QPen()] [, brush=QBrush()])
addEllipse(<QRectF>[, pen=QPen()] [, brush=QBrush()])

addPixmap ( <QPixmap>) -

( QGraphicsPixmapitem);

addSimplee~t (<> [,
font=QFont () J )

QGraphicsSimpleTextrtem, (0, )
;

addText (<> [,

font=QFont () J) -

QGraphicsextitem,

(0,

0) ;

addPath ( <QPainterPath> [, pen=QPen () J [, brush=QBrush ()]) - n


QGraphicsPathitem, ;

removertem(<QGraphicsitem>) - ( )
. , ,
. ,
QGraphicsitem, , QGraphicsEllipseitem (~;

+
+

clear () - . ;
createitemGroup (< >) ,
QGraphicsitemGroup;

destroyitemGroup ( <QGraphicsitemGroup>) - .

26.1.3.

. addWidget ()
QGraphicsscene. :

addWidget(<QWidget>[, flags=O])
, QWidget.

(. .

20.2).

( QGraphicsProxyWidget).

26.

581

, n setWindowi tle

()

QGraphicsWidget.

setActi veWindow ( <QGraphicsWidget>).


acti veWindow () .

n
,

26.1.4.

None.

n n QGraphicsScene~

itemAt () -

, n

None,

. :

itemAt(<X>, <>[, <QTransform>])


itemAt(<QPointF>[, <Qransform>])

t coll iding!tems (<QGraphicsitem> [, mode=IntersectsitemShape J ) -

, n n

. , n n;

t items ()

no

n , n

, , nn .

, n n. :

items ()
items(<Pe >)

items(<QPointF>)
items(<QPointF>,

< >,

deviceTransform=Qransform()

items(<X>,
items(<X>,

< >[,

])

<>,

<>,

<>[,

<>,

<>,

<>,

mode=IntersectsitemShape])
< >,

< >[, deviceTransform=QTransform()])


items(<QRectF>[, mode=IntersectsitemShape])
items(<QRectF>, < >, < >[,

deviceTransform=Qransform()])

items(<QPolygonF>[, mode=IntersectsitemShape])
items(<QPolygonF>, < >, < >[,
deviceTransform=Qransform()])

items(<QPainterPath>[, mode=IntersectsitemShape])
items(<QPainterPath>, < >, < >[,
deviceTransform=QTransform()])
n < >

n)

AscendingOrder
DescendingOrder ( n) QtCore.Qt.

n < >

mode

QtCore. Qt:

ContainsitemShape- - nn n,
;

IntersectsitemShape- 1 - nn n, n
n ;

582

1/.

ContainsitemoundingRect- 2 - ,

IntersectsitemoundingRect -

3-

26.1.5.

,
. ,
. ,

ItemisFocusale, ,

setFlag ()

c;Graphicsitem.
c;GraphicsScene:

setFocus ( [focusReason=OtherFocusReason]) ~ .
2 1.9. 1);

focusReason (. .

setFocusitem ( <c;Graphicsitem> [,

focusReason=OtherFocusReason] ) -

.
, .

None , ,
. focusReason
(. . 21. 9. 1);

. ,

clearFocus () -

, , ,
;

hasFocus () -

rue, , Fa~se

focusitem () None;

, ,

setStickyFocus

(<>)

True,

, ,
, , . ;

stickyFocus () -

rue,

, .

26.1.6.

( ),

ItemisSelectale, ,

setFlag ()
c;Graphicsitem.
QGraphicsScene:

setSelectionArea ()

QGraphicsitem. setSelectionArea ():


setSelectionArea(<QPainterPath>)
setSelectionArea(<QPainterPath>,

<>)

setSelected ()

26.

setSelectionArea(<QPainterPath>,
setSelectionArea(<QPainterPath>,

583
<Qransform>)
<>,

<Qransform>)

<> QtCore. Qt:

ContainsiternShape- - ,
;

IntersectsitemShape- l - ,
;

ContainsitemoundingRect-:- 2 - ,
;

IntersectsitemoundingRect- 3 - ,
;

+
+

selectionArea () - ( QPainterPath);
selecteditems () -

, ;

clearSelection () - . .

26.1.7.

QGraphicsscene
( ;
):

+
+

isActive () True, ,
False- ;
views () -

( QGraphicsView),

. ,
;

+
+

mouseGrabberrtem () - , ,
None, ;
render () -

. :

render(<QPainter>[, target=QRectF()] [, source=QRectF()] [,


mode=KeepAspectRatio])
target ,
source- .
, ;

invalidate () -

. :

invalidate(<X>, <>, <>, <>[, layers=AllLayers])


invalidate([rect=QRectF()] [, layers=AllLayers])
layers QGraphicsScene:

ItemLayer- l - ;

ackgroundLayer-

2 - ;

584

ForegroundLayer- 4 -

AllLayers- 65535-

11.

n n;

. n,

n n.
:

invalidate(const QRectF& = QRectF(),


QGraphiGsScene: :SceneLayers = QGraphicsScene.AllLayers)

update () -

n n .

update(<X>,

<>,

<>,

<>)

update([rect=QRectF()J)

QGraphicsScene

update (const QRectF& = QRectF ()).

changed (const QList<QRectF>&) -

n .

n n n n

sceneRectChanged(const

QRectF&)-

QRectF

n n;

n n n QRectF
;

select ionChanged () -

26.2.

n .

QGraphicsView.

QGraphicsView n .

n n. :

(QObject, QPaintDevice) - QWidget - QFrame QAstractScrollArea

- QGraphicsView

:
<>=

QGraphicsView([parent=None])

<>~ QGraphicsView(<QGraphicsScene>[, parent=None])

26.2.1.

J>I n n n

QGraphicsView (n ; n n

):

+
+
+

setScene ( <QGraphicsScene>) - n;
scene () - (n QGraphicsScene);
setSceneRect () - . :
setSceneRect(<X>,

<>,

<>,

<>)

setSceneRect(<QRectF>)

sceneRect () - n QRectF ;

26.

setackgroundBrush

585

( <QBrush>) - (

);

setForegroundBrush ( <QBrush>) -

);

setCacheMode (<>) - .
QGraphicsView:

+
+

cacheNone- - ;

CacheBackground- 1 - ;

resetCachedContent () - ;
setA1ignrnent (<>) -
.
. :

view.setA1ignment(QtCore.Qt.A1ignLeft

1 QtCore.Qt.AgnTop)

setinteractive (<>) - True,


(

). Fa1se ;

isinteracti ve () - rue, ,

Fa1se -

setDragMode (<>)- ,
. '

dragMode ().
QGraphicsView:

NoDrag- - ;
ScrollHandDrag- 1 -
.
;

RuberBandDrag- 2 - . ,
( setRuberBandSe1ectionode ())
, ( , ItemisSe1ectae).
;

setRuberBandSe1ectionode(<Pe>)-
RuberBandDrag. <>

QtCore. Qt:

ContainsitemShape- - ,
;

IntersectsitemShape- 1 - ,
;

ContainsitemoundingRect- 2 - ,
;

IntersectsitemoundingRect- 3 - ,
.

586

26.2.2.

11.

mapFrornScene (<>,

QGraphicsView:
<>)

mapFrornScene (<QPointF>) -

QPoint.

mapFrornScene(<X>, <>, <>,


mapFrornScene(<QRectF>)
mapFrornScene(<QPolygonF>)
mapFrornScene(<QPainterPath>)

<>)

->
->
->
->

mapToScene (<>, <>) mapToScene (<QPoint>) -

mapFrornScene () :

QPolygon
QPolygon
QPolygon
QPainterPath

QPointF.

maposcene

mapToScene(<X>, <>, <>,


mapToScene(<QRect>)
mapToScene(<QPolygon>)
mapToScene(<QPainterPath>)

26.2.3.

<>)

() :

-> QPolygonF
-> QPolygonF
-> QPolygonF
->.QPainterPath

itemAt () -

None,

, . :

itemAt (<>, <>)


itemAt(<QPoint>)

items () - ,
, , .

, .
, . :

items ()
items(<X>, <>)
items(<QPoint>)
items(<X>, <>, <>, <>[, mode=IntersectsiternShape])
items(<QRect>[, mode=IntersectsiternShape])
items(<QPolygon>[, mode=IntersectsiternShape])
items(<QPainterPath>[, mode=IntersectsitemShape])

mode . 26.1.4.

26.

26.2.4.

587

QGraphicsView:

translate (<>, <>) -

.
, - ;

rotate(<Yo>)-
( ).
, - ;

scale (< >, < >) - .-


. ,
, - ;

shear (<

>,

<

>)

resetatrix

() - .

.
, .
,

QMatrix,

26.2.5.

setMatrix ().

matrix ().

QGraphicsView
( ; n
):

centeron () -

. :

centerOn(<X>, <>)
centerOn(<QPointF>)
centerOn(<QGraphicsitem>)

ensureVisile

() -

. :

ensureVisible(<X>,

<>,

<>,

<>[,

xargin=SO]

[,

yargin=SO])

ensureVisible(<QRectF>[, xargin=SO] [, yargin=SO])


ensureVisible(<QGraphicsitem>[, xargin=SO] [, yargin=SO])

fi.tinView () -

.
:

fitinView(<X>, <>, <>, <>[, mode=IgnoreAspectRatio])


fitinView(<QRectF>[, mode=IgnoreAspectRatio])
fitinView(<QGraphicsitem>[, mode=IgnoreAspectRatio])

588

11.

render () -
. :

render (<QPainter> [, target=QRectF () ] [, source=QRectF () ] [,


mode=Keep~spectRatio])

invalidateScene ( [ rect=QRectF () ] [,

layers=AllLayers] ) -

.
:

invalidateScene(const QRectF& = QRectF(),


QGraphicsScene::SceneLayers = QGraphicsScene.AllLayers)

updateSceneRect (<QRectF>)-
updateSceneRect (n QRectf&);

updateScene (<n n QRectF>) -

updateScene (const

QList<QRectf>&).

26.3.

QGraphicsltem.

QGraphicsrtem .

QGraphicsltem ( [parent=None] [, scene=None])


parent ( ,
QGraphicsrtem). scene
(

QGraphicsScene).

QGraphicsitem , .
, QGraphicsitem

boundingRect () paint (). undingRect ()


QRectF ,
. paint () .
paint () :

paint(self, <QPainter>, <QStyleOptionGraphicsitem>, widget=None)

shape ().

26.3.1.

QPainterPath.

QGraphicsitem ( ;
):

setPos () -

). ~:

setPos(<X>, <>)
setPos(<QPointf>)

26.

+ pos ()

589

QPointF

( );

QPointF

scenePos () ;

sceneBoundingRect () -

QRectF, -

( ) , ;

+
+
+

setx (<>) setY (<>) - ;


() () - ;

setZValue (<Z>) - z.
.
.;

+
+

zValue () -

moveBy (< >,

<

>)

z;

prepareGeometryChange () -

, ;

+
+

scene () None;

( QGraphicsScene)

setFlag (<> [, enaed=True]) - (


True) ( False) .

QGraphicsitem

( ; ):

ItemisMovae-

ItemisSelectae- 2- ;

ItemisFocusae- 4- ;

Oxl- ;

ItemignoresTransforations- 20-
;

ItemignoresParentOpacity- 40- ;
ItemDoesntPropagateOpacityoChildren- -
;

OxlOO -

ItemStacksBehindParent -

ItemisPanel- 4000- ;

setFlags (<>) - . (.
setFlag ()) 1;

flags ()
setFlag () );

setOpacity (<>) -

(.

. ( ) 1. ( -

);

opaci ty () - ;

11. h

590

t
t

setoolTip (<>) - ;

setCursor (<>) (. .

t
t

21.10.5);

unsetCursor () - ;
setVisie (<>) - True,
. False ;

t
t
t
t

show () - ;
hide () - ;
isVisie () -

True, , False- ;

setEnaed (<>) -

True,

. False .
;

isEnaled () -

True, , False-

setSelected (<>) -

True,

. False . ,

ItemisSelectae, , setFlag ()

QGraphicsrtem;

isSelected () - True, , False-


;

setFocus ( [focusReason=OtherFocusReason]) .
focusReason (.
.

21.9.1).

ItemisFocusale, ,

t
t

setFlag ()

QGraphicsitem;

clearFocus () - ;
hasFocus () True, ,
False- ;

grabKeyboard () - ;

t
t
t

ungrabeyboard () - ;

grabMouse () - ;
ungrabMouse () - .

26.3.2.

QGraphicsrtem:

translate (<>,

<>) -

.
, - ;

rotate(<Yo>)-

( ). 4
,

.:...._

26.

591

scale (< >, < >) - .


. ,

, - ;

shear (< >,

<

>)

resetMatrix () - .

.
, .
,

QMatrix, setatrix ().


rnatrix ().
sceneatrix ().

, Qatrix,

QTransform.
setTransform (), transform ().
sceneTransform ().
setTransform ()
QGraphicsrtem:

setransformOriginPoint (<>,

<>)

. :

setTransformOriginPoint(<X>,

<>)

setTransformOriginPoint(<QPointF>)

setRotation (<>) -

( . ).
, - ;

+
+

rotation () -

setScale (<>)- .
. ,

, - ;

+
+

scale () -

resetTransform () - .

26.3.3.

QGraphicsrtem

( ;
):

setparentitem(<QGraphicsitem>)- . ;

+
+
+
+

parentitern () - ;
topLevel Item () -

childiterns () - ;
collidingrterns ( [rnode=IntersectsiternShape]) -

, . ,
. rnode . .

26.1.4;

592

11.

collidesWithitem (<QGraphicsitem> [, mode=IntersectsitemShape] ) -

rue, , n n.

n mode . . 26.1.4;

ensureVisie () -

n , n

n. :
ensureVisie (<>,

<>,

<>,

<>

[,

xargin=SO]

[,

yMargin=50])
ensureVisile([rect=QRectF()]

[,

xargin=SO]

[,

yargin=SO])

update (<QRectF>) - n n .
:

update(<X>, <>, <>,


update([rect=QRectF()])

26.4.

<>)

, n QGraphicsitem,
n :

+
+
+
+
+
+
+
+
+

QGraphicsLineitem- ;
QGraphicsRectitem- n;
QGraphicsPolygonitem- ;
QGraphicsEllipseitem- n;
QGraphicsPixmapitem--:- ;
QGraphicsSimpleTextitem- n ;
QGraphicsextitem- ;

QGraphicsPathitem- n;
QGraphicsSvgitem- SVG-.

26.4.1.

QGraphicsLineitem n . :

QGraphicsitem - QGraphicsLineitem
:
<>=
<>=

<>=

QGraphicsLineitem([parent=None] [, scene=None])
QGraphicsLineitem(<Xl>, <Yl>, <2>, <2>[, parent=None] [,
scene=None] )
QGraphicsLineitem(<QLineF>[, parent=None] [, scene=None])

n parent , n scene .

QGraphicsLineitem QGraphicsitem
(n ; n n
):

26.

setLine ()

- . :

setLine(<Xl>, <Yl>,
setLine(<QLineF>)

<2>,

<2>)

line ()

setPen (<QPen>)

26.4.2.

593

QLineF;

- .

QAbstractGraphicsShapeltem

QAstractGraphicsShapeitem

QGraphicsitem -

QAstractGraphicsShapeitem

QAstractGraphicsShapeitem (
; n ):
- ;

setPen (<QPen>)

setBrush ( <QBrush>)

26.4.3.

- .

QGraphicsRectitem n n. :

QGraphicsitem -

QAstractGraphicsShapeltem

- QGraphicsRectitem

QGraphicsRectitem([parent=None] [, scene=None])
= QGraphicsRectitem(<X>, <>, <>, <>[,
parent=None] [, scene=None])
<>= QGraphicsRectitem(<QRectF>[, parent=None] [, scene=None])
<>

<>

parent , scene-

QGraphicsRectrtem

(n ; n ):

setRect ()

- . . :

setRect(<X>, <>,
setRect(<QRectF>)

rect ()

26.4.4.

<>,

<>)

- n

QRectF.

QGraphicsPolygonitem n . :

QGraphicsitem -

QAstractGraphicsShapeitem

- QGraphicsPolygonitem

:
<>=
<>=

QGraphicsPolygonitem([parent=None] [, scene=None])
QGraphicsPolygonitem(<QPolygonF>[, parent=None] [, scene=None])

594

11.

parent ~ , scene-

QGraphicsPo1ygonitem

( ;
):

t setpo1ygon (<QPo1ygonF>) - ;
t po1ygon () - QPo1ygonF.

26.4.5.

QGraphicsEllipseitem . :

QGraphicsitem -

QAstractGraphicsShapeitem

- QGraphicsE11ipseltem

:
<>=
<>=

<>=

QGraphicsE11ipseitem([parent=None] [, scene=None])
QGraphicsE11ipseitem(<X>, -<>, <>, <>[,
parent=None] [, scene=None])
QGraphicsE11ipseitem(<QRectF>[, parent=None] [, scene=None])

parent , scene-

QGraphicsEllipseitem

( ;
):

t setRect () -

, .

setRect(<X>, <>,
setRect(<QRectF>)

<>,

<>)

t rect () - QRectF;
t setStartAng1e (<>) setSpanAng1e (<>)

. ,
1/16 . 16 * 360.
.
, ;

t startAng1e ()

spanAng1e () -

26.4.6.

QGraphicsPixrnapitem . :

QGraphicsitem - QGraphicsPixmapitem
:
<>=
<>=

QGraphicsPixrnapitem([parent=None] [, scene=None])
QGraphicsPixrnapitem(<QPixrnap>[, parent=None] [, scene=None])

parent , scene .

26.

595

QGraphicsPixrnapitem QGraphicsitern
( ;
):

t
t
t

setPixrnap (<QPixrnap>) - ;
pixrnap () - QPixrnap;
setOffset () - . :
setOffset.(<X>, <>)
setOffset(<QPointF>)

t
t

offset () - ( QPointr);
setShapeMode (<>) -

QGraphicsPixrnapitern:

MaskShape- -
QPixrnap ( );

oundingRectShape- 1 - ;

HeuristicaskShape-

2-

createHeuristicask()

setTransforrnationode (<>) -

rnask ()

QPixrnap;
.

QtCore .Qt:

FastTransforrnation- - ( );

SrnoothTransforrnation- 1 -

26.4.7.

QGraphicsSirnp1eTextitern . :

QGraphicsitern -

QAstractGraphicsShapeitern

- QGraphicsSirnpleTextitern

:
<>=

QGraphicsSirnp1eTextitern([parent=None] [, scene=None])
parent=None] [, scene=None])

<>= QGraphicsSirnp1eTextitern(<Tec>[,

parent , scene .

QGraphicsSirnp1eTextitern
( ;
):

setText (<>) - ;

text () -

setFont (<QFont>) - ;

font () - ( QFont).

26.4.8.

QGraphicsTextitern . :

(QObject, QGraphicsitem) - QGraphicsObject - QGraphicsTextitem

596

11.

QGraphicsTextitem([parent=None] [, scene=None])
parent=None] [, scene=None])

<>=

<>= QGraphicsTextitem(<Tec>[,

n parent , n scene .

QGraphicsextitem

(n ; n n ):

+
+
+
+
+
+
+
+

setPlainText (< >) - n ;


toPlainText () -

n ;

setHtml (<L->) - L-;


toHtml () - L-;
set Font ( <QFont >) -

font () - (n QFont);
setDefaul tTextColor (<QColor>) - no ;
setTextWidth (<>) - nn . n
, n ;

+
+
+

textWidth () - nn ;

document () - (n QTextDocument;
. .

(n

setDocument (<QTextDocument>) QTextDocument; . . 23.6.4);

23.6.4);

setextCursor(<QextCursor>)-

(n

QTextCursor; . . 23.6.5);

textCursor () .

(n

QTextCursor;

23.6.5);

setTextinteractionFlags (<>) - n
. n NoTextinteraction, n n
. n n .
(. n

23.1

setTextinteractionFlags () );

setTabChangesFocus (<>) -

n False,

n <> .
rue, <> n n ;

setOpenExternalLinks (<>) -

n rue,

n n , n

no

, . n n

TextBrowserinteraction.

QGraphicsextitem :

linkActivated (const QString&) -

n n

no

n.

n n URL-apec;

linkHovered (const QString&) - n n


. n n URL-apec
n .

26.

26.5.

597

QGraphicsrtemGroup.

nn n n, n n

(NraphicsitemGroup

nn.

(Nraphicsitem - QGraphicsitemGroup
:
<>=

QGraphicsitemGroup([parent=None] [, scene=None])

n parent , n scene .

QGraphicsitemGroup QGraphicsrtem

(n ; n n
):

+
+

addToGroup (<QGraphicsrtem>) - n;
removefromGroup (<QGraphicsitem>) - nn.

createitemGroup(<Cco >)

QGraphicsScene.
n (n QGraphicsrtemGroup). n n
destroyitemGroup ( <QGraphicsitemGroup>) QGraphicsScene.
n n

setGroup(<QGraphicsrtemGroup>)

QGraphicsrtem. n, nn . n
group () QGraphicsitem. nn n,

26.6.

None.

n , n n

QGraphicsEffect nn draw (), .


n n

+
+

QGraphicsitem:

setGraphicsEffect ( <QGraphicsEffect>) - ;
graphicsEffect () -

None,

26.6.1.

QGraphicsEffect

QGraphicsEffect .
:

QObject - QGraphicsEffect
:

QGraphicsEffect([<QObject>])

598

11,

QGraphicsEffect (
; ):

draw(self,

<QPainter>)- .

setEnaed (<>) -

False,

. True .
setEnaed(bool);

isEnaed () -

False-

True, ,

update () - . .

QGraphicsEffect enaedChanged (bool),

. rue,
, False- .

26.6.2.

QGraphicsDropShadowEffect : . :

QObject - QGraphicsEffect - QGraphicsDropShadowEffect


:
<>=

QGraphicsDropShadowEffect([<QObject>])

QGraphicsDropShadowEffect
( ;
):

setColor(<QColor>)- . QColor(63,
63, 63, 180). setColor (const QColor&);

+
+

color () - ( QColor);

..

setlurRadius (<>) setlurRadius

+
+

. ~

(qreal);

urRadius () - ;

setOffset () - . :
setOffset(<o >,

< 9 >)

setOffset(<QPointF>)
setOffset(<Ceee>)

setOffset(qreal,qreal)
setOffset(const QPointF&)
setOffset (qreal)

+
+

offset () - ( QPointF);
setXOffset (<>) - .
setXOffset (qreal);

xOffset () -

> ;

599

26.

+ setYOffset (<>) - .

setYOffset (qreal);

+ yOffset () - .

QGraphicsDropShadowEffect

+ colorChanged (const

QColor&) -

+ lurRadiusChanged(qreal)-

QColor);

+ offsetChanged (const

QPointF&) -

26.6.3.

QPointF).

QGraphicsBlurEffect

. :

QObject - QGraphicsEffect - QGraphicsBlurEffect


:
<>=

QGraphicsBlurEffect((<QObject>])

QGraphicsBlurEffect

( ; ):

t setBlurRadius (<>) t

lurRadius

. -

setBlurRadius (qreal);

()

- .

QGraphicsBlurEffect

blurRadiusChanged (qreal),

n .
.

26.6.4.

QGraphicsColorizeEffect

. :

QObject - QGraphicsEffect - QGraphicsColorizeEffect


:
<>=

QGraphicsColorizeEffect([<QObject>])

QGraphicsColorizeEffect

( ;
):

t setColor (<QColor>) 255).

QColor (,

192,

setColor (const QColor&);

t color () - ( QColor);
t setStrength (<>) - .

. l. ( ).

t strength ()

setStrength (qreal);

- .

600

11.

l(

QGraphicsColorizeEffect :

colorChanged(const QColor&)- n .
n n (n QColor);

n .

strengthChanged (qreal) -

n n .

26.6.5.

QGraphicsOpacityEffect n. :
QObject - QGraphicsEffect - QGraphicsOpacityEffect
:
<>=

QGraphicsOpacityEffect([<QObject>])

QGraphicsopacityEffect
(n ; n n
):

setOpaci ty (<>) -

n n1.

. 1. . n . 7.

+
+

opaci ty () -

setOpacity (qreal);

n n;

setOpacityMask(::=Qrush>)-

setOpacityMask(const QBrush&);

opaci tyMask () -

QGraphicsOpacityEffect :

opacityChanged(qreal)- n n n.
n n ;

opaci tyMaskChanged ( const QBrush&) - n .

26.7.

n n, n n
n . n ,

n . n, n ,
n .

n
, ?JI.

21.

26.7.1.

, :

n . !!
ItemisE'ocusae, n, n setE'lag ()

QGraphicsitem;

26.

. , ,
.

601

26.1.5 26.3.1;

grabKeyboard (), - ungrabKeyboard ();

, <>

<Shift>+<Tab>.

, accept ()

ignore ().

,
, :

focusinEvent (self,

<event>) -

<event> QFocusEvent (. .

focusOutEvent ( self,

<event>) -

21. 9. !);

<event> QFocusEvent (. . 21.9.1);

keyPressEvent (self, <e,:,ent>) - .


, ,
.
.

<event>

QKeyEvent (.

21.9.3);

keyReleaseEvent (self, <event>) - .


<event> QKeyEvent (. .

21.9.3).

setFocusProxy ( <QGraphicsitem>) QGraphicsitem


, .
focusProxy ().

26.7.2.

,
, :

mousePressEvent (self,

<event>) -

. <event> QGraphicsSceneMouseEvent.
, accept () ,
ignore (). ignore (),

mouseReleaseEvent () mouseMoveEvent () .
setAcceptedouseButtons (<>) QGraphicsitem
, .

. <> NoButton
QtCore .Qt, ;

+ 'mouseReleaseEvent (self,

<event>) -

. <event> QGraphicsSceneMouseEvent;

mouseDouleClickEvent (self,

<event>) -

<event>

QGraphicsSceneMouseEvent;

mouseMoveEvent (self, <event>) -


. <event> QGraphicsSceneMouseEvent.

602
QGraphicsSceneMouseEvent
QEvent :

pos () -

11.

QGraphicsSceneEvent

QPointF

+
+
+

scenePos ()

screenPos () -

QPointF

QPoint ;
QPointF ~;~ -

lastPos () -

lastScenePos () -

QPointF

lastScreenPos () -

QPoint

buttonDownPos (<>) -

QPointF

buttonDownScenePos (<>) - QPointF


;

buttonDownScreenPos (<>)- QPoint


;

+
+
+

button () -

, ;

buttons () modifiers () -

<A\t>

, ;

, -

(<Shift>, <Ctrl>,

.) .

,
. t ,
grabMouse () QGraphicsitein.
ungrabMouse (). ,
,

mouseGrabberitem()

QGraphicsScene.

,
, :

hoverEnterEvent (self, <event>)

<event>

QGraphicsSceneHoverEvent;

+
+

hoverLeaveEvent (self, <event>) -,


. <event> QGraphicsSceneHoverEvent;
hoveroveEvent (self,

<event>) -

<event>

QGraphicsSceneHoverEvent;

wheelEvent (self,

<event>) -

. ,

QGraphicsSceneWheelEvent.

<event>

26.

603
hoverEnterEvent (), hoverLeaveEvent () hoverMoveEvent ()

, .

setAcceptHoverEvents (<>) QGraphicsitem n True.


False n n .
n :r acceptHoverEvents ().
QGraphicsSceneHoverEvent QGraphicsSceneEvent
QEvent :

+ pos () -

n QPointF n -

+ scenePos () - n QPointF n ;
+ screenPos () - n QPoint n ;
+ lastpos () - n QPointF n n
n n n ;

lastScenePos () -

QPointF n

n n n n ;

lastScreenPos () -

n QPoint n

n n n n ;

+ modifiers () <Ait>

n n, - (<Shift>, <Ctrl>,

.) .

QGraphicsSceneWheelEvent QGraphicsSceneEvent
QEvent :

+
+

delta () - n ;

o~ientation () -
QtCore.Qt:

Horizontal- 1 - no

Vertical -

2 ~ no

pos () - n QPointF n
;

n QPointF

scenePos () -

n ;

n QPoint

screenPos () -

n ;

buttons () -

n n n, q n

modifiers()- n n, - (<Shift>, <Ctrl>,

<Ait>

26.7 .3.

.) .

n , ,

setAcceptDrops ()

QGraphicsitem

True.

604

11.

n n :

dragEnterEvent () n I-n n

. n .

' , acceptProposedAction ()
. , setDropAction () n

accept (),

acceptProposedAction();

,
n <;>n dragMoveEvent (). n
n n .

accept ();

dropEvent () n .

, n n , n
:

dragEnterEvent (self, <event>) -, n


. n <event> n n
QGraphicsSceneDragDropEvent;

dragLeaveEvent (self, <event>)

, n n

. n <event> n n

QGraphicsSceneDragDropEvent;

dragMoveEvent (self,

<event>) -

n n

<event> n n

QGraphicsSceneDragDropEvent;

dropEvent (self, <event>)- n .

n
<event>
n
n

QGraphicsSceneDragDropEvent.

oGraphicsSceneDragDropEvent . QGraphicsSceneEvent
QEvent :

mimeData () -

QMimeData n

t-n;

pos () - n QPointF n
;

scenePos () - n QPointF n ;

screenPos () - n QPoint n ;

possieActions () - n ;

proposedAction () - n ;

acceptProposedAction () -

n n

setDropAction (<>) -

n n .

dropAction () ;

proposedAction ();

accept (), acceptProposedAction ();

, n n

26.

+ modifiers ()
<Ait>

+
+

605

, -

( <Shift>, <Ctrl>,

.) ;

buttons () - , ;
source () - None.

26.7.4.
,
.

sceneEvent (self,

<event>)

. <event>
. .
rue, , False- .

True, (, mousePressEvent ())

- ,

sceneEventFilter(self, <QGraphicsitem>, <event>) .


<QGraphicsitem> , <event>-

.
.

rue, ,

False- . True, .
, ,

QGraphicsitem:

installSceneEventFilter(<QGraphicsitem>)- ,
;

+
+

removeSceneEventFilter(<QGraphicsitem>) - ;
setFiltersChildEvents(<a>)- True,
.

26.7 .5.

itemChange(self,

<>,

<>) .

. <> , ,

QGraphicsitem (

; ):

+
+

ItemEnaedChange- 3 - ;

ItemEnaedHasChanged- 13- .
;

+
+

ItematrixChange- l - ;

ItemPositionChange- - . ,
ItemSendsGeometryChanges;

ItemPositionHasChanged- 9 - .. ,
ItemSendsGeometryChanges.
;

11.

ItemScenePositionHasChanged- 27- .
, ItemSendsScenePositionChanges.
;

+
+

ItemTransformChange- 8 - . ,
ItemSendsGeometryChanges;
ItemTransformasChanged- 10- .
, ItemSendsGeometryChanges.

+
+

ItemSe1ectedChange- 4 - ;
ItemSe1ectedasChanged- 14- .
;

+
+

ItemVisieChange- 2 - ;
ItemVisieHasChanged- 12- . ;

+
+
+
+

ItemCursorChange- 17 -

ItemcursorHasChanged- 18- . ;
ItemToolTipChange- 19- ;
ItemToolTipHasChanged- 20- .
;

+
+
+
+

ItemFlagsChange- 21- ;
ItemFlagsHaveChanged- 22- . ;
ItemZValueChange -

23 -

ItemZValueHasChariged- 24 -

z;

z.

+
+

ItemOpacityChange- 25- ;
ItemOpacityHasChanged- 26- .
.

BHHMAHHEI

i temChange ( )

li;

QGraphicsitem.

27

,
.

(. . )
.

PyQt

QDialog, ,

;r

QDialog , .
, QMessageBox ,

QinputDialog- , QFileDialog-

. .

PyQt
QPrintDialog)
QPrintPreviewDialog).

27 .1.
QDialog .
, .
.

QDialog :

(QObject, QPaintDevice) - QWidget - QDialog


QDialog :
<>= QDialog([parent=<Poe>]

[,

flags=<Tn >])

parent .
None, .
,
. , ,

, .

-

Dialog.

flags, . 20.2.

608

11:

QDiaiog n
( ; n n
):

_ () -

QDialog:

Accepted- 1 - n ;

Rejected- - ~ n

Cancel,

n -

<Esc>.

int ().


n (

MyDialog QDialog, window-

):

def on_clicked():
dialog = MyDialog(window)
result = dialog.exec_()
if result == QtGui.QDialog.Accepted:
pr int (" n ")
# n
else:
print (" n Cancel")

accept () -

Accepted QDialog. . accept ()

n :

self.btnOK.clicked.connect(self.accept)

reject () -

Rejected QDialog. . reject ()


n

Cancel:

self.b~nCancel.clicked.connect(self.reject)

done (< >) - n. done ( int) ;

+
+
+

setResult (< >) - ;


result () - ;
n,

setExtension (<QWidget>) -

. ,
;

extension () -

n, n

showExtension (<>) -

None;

True,

, False- .

toggled (bool)

showExtension (bool).

n-:

27.

self.btnExt

609

= QtGui.QPushButton("&oe

... ")

self.btnExt.setCheckale(True)

self.btnExt.toggled("bool"] .connect(self.showExtension)

setOrientation (<>) :-
. QtCore. Qt:

orizontal- 1 - ( );

Vertical- 2 -

setSizeGripEnaed (<>) -

True,

False- ( );

isSizeGripEnaed

rue,

() -

, False- ;

setVisie (<>) - True,


,

open () -

show ()

False- .
hide () QWidget;

, . ;

setModal (<>) -

True,

to

, False- . , ,
_ (),

setModal (.). ,
show () setVisie (). i

raise_() ( ) activateWindow() (
( )).
,

setWindowModality(<a>)

QWidget.
QtCore.Qt:

Nonodal- - ;

WindowModal- 1 - ;

Applicationodal- 2 - .

, , . ,
setWindowModality () .
windowModality () QWidget.
isModal ()
QWidget. . True, , False-
, ,

QDialog :

accepted () -

Accepted ( ).

hide ()

setVisie

();

rejected () - Rejected ( Cancel, n


<Esc>).

20 . 1349

hide ()

setVisie

();

610

11.

, ,

finished ( int) -

accept (), reject () . done ().


.

hide ()

setVisile

().

setAutoDefault () True.
~ n

<Enter>,

n , .

n n <>.
setDefault () n

<Enter>,

no

. n

, .

27 .2.

QDia/ogButtonBox

QDialogButtonox ,
, , .
.

QDialogButtonBox:

(QObject, QPaintDevice) - QWidget - QDialogButtonBox



<>=

QDialogButtonBox:

QDialogButtonBox([parent=None])

<>= QDialogButtonBox(<Opea>[,
<>

QDialogButtonBox(<Caape

parent=None])

n>[,

orientation=Horizontal] [, parent=None])
parent .
<>

orientation

Horizontal ( ;
) vertical ( ) QtCore .Qt. < n>

QDialogButtonox:

+
+
+
+
+
+
+
+
+
+
+

NoButton- ;
Ok- AcceptRole;
cancel-
Yes-
YesToAll -

Yes

No-
NoToAll -

No

Open-

Save-

YesRole;

NoRole;

No to All

NoRole;

AcceptRole;

Close

Save

RejectRole;

YesRole;

Yes to Afl

Open

Close-

SaveAll -

Cancel

RejectRole;

AcceptRole;

Save All

AcceptRole;

1)

27.

Discard-

611

Discard Don't Save (

) DestructiveRo1e;

+
+
+
+
+
+
+

1-

Apply

App1yRo1e;

Reset-

Reset

RestoreDefaults-
1-

Help

Abort

Retry-

Retry

Ignore -

Restore Defaults

Aort-

ResetRo1e;

RejectRo1e;

AcceptRo1e;

lgnore

ResetRo1e;

He1pRo1e;

AcceptRo1e.

+
+
+

QDia1ogButtonBox:

Inva1idRo1e- - 1 - ;
AcceptRo1e- - '
Accepted;
RejectRo1e- 1 -
Rejected;

+
+

DestructiveRo1e- 2 - ;
ActionRo1e- - , ;

+
+
+
+
+

He1pRo1e- 4 -

YesRo1e- 5 -

NoRo1e- -
ResetRo1e- 7 -

Yes;

No;

App1yRo1e- - .

QDia1ogButtonBox
( ;

):

setOrientation(<Opea>)-
. Horizonta1 ( )

vertica1 ( ) QtCore .Qt;

setStandardButtons (<

>) -

. :

se1f.box.setStandardButtons(QtGui.QDia1ogButtonBox.Ok
QtGui.QDia1ogButtonBox.Cance1)

addutton(<QAstractButton>,

<>)-

. ,
- . , . :

se1f .btnOK

QtGui .QPushButton ("&")

se1f.box.addutton(se1f.btnOK,

QtGui.QDia1ogButtonBox.AcceptRo1e)

612

1/.

addButton (< >) -


. , None.
:

self.btnOK

self.box.addButton(QtGui.QDialogButtonBox.Ok)

addButton (<>,

<>) - ,

. <>

QPushButton.
None.

, ,
:

self.btnOK

self.box.addButton("&OK",
QtGui.QDialogButtonBox.AcceptRole)

uttn(< >)- ,
,
;

None.

buttonRole (<QAstractButton>) - .

InvalidRole;

buttons () - ,
;

remveButton (<QAstractButton>) - ,

'

clear () - ;

setCenterButtons (<>) - rue,


.

QDialogButtonox :

accepted () -

A<;:ceptRole YesRole.

accept () . :

self.box.accepted.connect(self.accept)

rejected () -

RejectRole NoRole.

reject () . :

self.box.rejected.connect(self.reject)

+
+

helpRequested () - HelpRole;
clicked (QAstractButton *) -

. .

27 .3.

QMessageBox

QMessageBox .

QMessageBox

(QObject, QPaintDevice) - QWidget - QDialog - QMessageBox

27.

613
QMessageBox:

<>

QMessageBox([parent=None])

<>

Qssg(<>,

<

>,

<

>[,

buttons=NoButton] [ , parent=None] [,
flags=Dialog 1 MSWindowsFixedSizeDialogHint])
n

parent ,

, .

flags n (. . 20.2). n <>


QMessageBox:

Noicon- - ;

Question- 4 -

+
+
+

Information- 1 - ;

n;

warning- 2 - nn ;
Critical- - .

n buttons ( n

+
+
+
+
+
+

1)

QMessageBox:

NoButton- n ;
Ok- n AcceptRole;
Cancel- n Cancel RejectRole;
Yes- n Yes YesRole;
YesToAll- n Yes to All YesRole;
No- n No NoRole;

NoToAll- No to All NoRole;

+
+
+
+
+

Open- n Open AcceptRole;


Close- n Close RejectRole;
Save -

Save

AcceptRole;

SaveAll- n Save All AcceptRole;


Discard- n Discard Don't Save (n n n
) DestructiveRole;

+
+
+
+
+
+
+

Apply- n Apply ApplyRole;


Reset- n Reset ResetRole;
RestoreDefaults- Restore Defaults ResetRole;
Help- n Help HelpRole;
Aort-

Abort

RejectRole;

Retry- n Retry AcceptRole;


Ignore- n lgnore AcceptRole.

n .
QMessageBox:

614

+
+
+

11.

Invalid.Role- - 1 - ;
AcceptRole - Accepted;

RejectRole- 1 - .
Rejected;

+
+

DestructiveRole- 2 - ;
ActionRole-

- , -

+
+
+
+
+

HelpRole- 4 - ;
YesRole- 5 - Yes;
NoRole -

ResetRole- 7 -

No;

ApplyRole- - .

_ () .
. :

dialog

= QtGui.QessageBox(QtGui.QMessageBox.Critical,
" ",

" ",

buttons = QtGui.QessageBox.Ok
QtGui.QMessageBox.Cancel,
parent=window)
result

27 .3.1.

dialog.exec_()

QMessageBox
( ;
):

+
+

seticon (<>) - ;

, .

seticonPixmap ( <QPixmap>) -

+
+

QPixmap;

setWindowitle (< >) - ;


setext (<

>) -

HTML.

\n,

HTML

<br>;

setinformativeText (<>).- ,
. ,

HTML;

setDetailedText (<>) -

Show Details,

setTextFormat (<>) -

QtCore.Qt:

27.

PlainText -

Richext -

615

1-

AutoText- 2 - ( ).
, Rici1Text,
PlainText;

setStandarduttons (<

n1>)

. :
dialog.setStandarduttons(QtGui.QessageBox.Ok
QtGui.QessageBox.Cancel)

addutton(<QAstractButton>,

<>)- .

. :

btnYes

QtGui .QPushButton ("&")

dialog.addBu~ton(btnYes,

QtGui.QessageBox.AcceptRole)

dduttn(< >)-
. ,

btnSave

None. :

dialog.addButton(QtGui.QMessageBox.Save)

addutton(<Tec>,

<>)- ,

. <>

QPushButton.
None. :

, ,

btnYes

= dialog.addutton("&a",

QtGui.QessageBox.AcceptRole)

setDefaul tButton () - . :
setDefaultButton~<Caapa >)

setDefaultButton(<QPushButton>)

setEscapeButton () - , <Esc>.
:
setEscapeButton(<Caapa

>)

setEscapeButton(<QAstractButton>)

+
+

clickedButton () None;

, ,

button (< >) -

, None,
;

buttonRole (<QAstractButton>)- .
, InvalidRole;

+
+

buttons () - , ;
removeButton(<QAstractButton>)- ,
.

QMessageBox buttonClicked (QAstractButton *),


~ . l!
.

616

27 .3.2.

11.

QMessageBox

, .
n
information(<Poe>,

< >,

information ().

< >[,

buttons=Ok] [, defaultButton=NoButton])
n <>

None.

, . n

buttons n

n (, n,

1). n . defaultButton
no . information () n. :

n
n

" ",

QtGui.QMessageBox.information(window,
"

",

buttons=QtGui.QMessageBox.Close,
defaultButton=QtGui.QMessageBox.Close)
n n .

27 .3.3.

27.1.

27.1.

n n - n

question ().

question(<Poe>,

<

:
>,

< >[,

buttons=Ok] [, defaultButton=NoButton])
n <>

None.

, . n buttons n
n (, n,

1).

n
n

no

result =

n .

question ()

defaultButton

n. :

QtGui.QessageBox.question(window,
"

" ",

m ?",

buttons=QtGui.QessageBox.Yes 1 QtGui.QMessageBox.No
QtGui.QMessageBox.Cancel,
defaultButton=QtGui.QMessageBox.Cancel)

n n .

27.2.

617

27.

27.2.

27.3.4.

warning ().

warning(<Poe>,

< >,

< >[,

buttons=Ok] [, defaultButton=NoButton])
<>

None.

, .

buttons

(, ,

1).

result =

defaultButton
warning () . :

QtGui.QessageBox.warning(window,
"

" ",

buttons=QtGui.QessageBox.Yes

?",

1 QtGui.QMessageBox.No

QtGui.QMessageBox.Cancel,
defaultButton=QtGui.QessageBox.Cancel)

27.3.5.

27.3.

27.3.

critical

(). :

ritil(<>,

< >,

< >[,

buttons=Ok] [, defaultButton=NoButton])
<>

None.

,
, .

buttons

(, ,

618

1).

11.

. defaultutton

. critical () . :
QtGui.a-lessageBox.critical(window,

" ",

" nn ",

buttons=QtGui.QMessageBox.Ok,
defaultButton=QtGui.a-lessageBox.Ok)
.

27.4.

27.4.

" "

27 .3.6.


3
ut(<>,

about ().

< >,

< >)

<>

None.

, t~
, .
(. .

20.9),

. :

QtGui.a-lessageBox.about(window,

27 .3. 7.

" ",

"n

n")

"About Qt"
Qt

<>

None.

aboutQt ().

utQt(<>[,

title=QString()])

,
, .

ti tle

. ,

"About Qt".

QtGui.a-lessageBox.aboutQt(window)

27 ~4.

QlnputDialog

QinputDialog .
QinputDialog :

(QObject, QPaintDevice) - QWidget - QDialog - QinputDialog

27.

619


<>=

QinputDialog:

QinputDialog([parent=None] [, flags=O])

parent ,
, .

flags (. . 20.2).
_ () .
QDialog;
Accepted Rejected.
:

def on_clicked():
dialog = QtGui. QinputDialog (window)
result = dialog.exec_()
if result == QtGui.QDialog.Accepted:
print (" ")
#
else:
print (" Cancel")

27 .4.1.

Qinputoialog

( ; ~I
):

t
t

setLabel t (<>) - , ;
setOkButtonText (<>) - , :
dialog.setOkButtonText("&Bo")

setCancelButtonext (<>) - ,

Cancel.

dialog.setCancelButtonText("&Oea")

setinputMode (<>) - .
QinputDialog:

- ;

Textinput-

Intinput- 1 -

Doueinput-

2-

setextEchoMode (<>)- .
QLineEdit:

Normal- - ;

NoEcho- 1 -

Password- 2 -

PasswordEchoOnEdi t ~

*;

*;

setextValue (<>) - , ;

620

+
+

11.

textValue () - , ;
setintValue (<>) -
Intinput;

+
+

, ,

intValue ()

Intinput;

setintRange (<>,

<>),

setintMinimum (<>)

setintMaximum(<acy>)-

Intinput;

setintStep(<Illa>)-

Intinput;

setDouleValue (<>) -
Douleinput;

douleValue

, ,

() -

Douleinput;

setDouleRange(<y>,

<>),

setDouleMaximum (<>)

setDouleMinimum(<y>)

Douleinput;

setDouleDecimals (<>) -
Douleinput;

setComoBoxitems (< >) - ,


;

setComoBoxEditae (<>)

True,

setOption(<O>[,

on=True])- True,
False-

QinputDialog:

NoButtons- 1 - ;

UseListViewForComoBoxitems- 2 - JI

setOptions (<>) setOption ()).

QListView,

QComoBox;

(.

QinputDialog :

textValueChanged (const QString&) -

. .
extinput;

textValueSelected (const QString&) -

.
extinput;

intValueChanged ( int) -

Intinput;

27.

intValueSelected ( int) -

621
.

Intinput;

douleValueChanged(doule)- .
.
Douleinput;

douleValueSelected (doule) -

.
Douleinput.

27 .4.2.

QinputDialog

, . JJ)I
getext
gtt(<>,

< >,

().

< >[,

mode=Normal] [, text=QString()J [, flags=OJ)


<>

None.

,
, .

mode
27.4.1). text
, n flags n .
getext () : (<>, <>).
(. setextEchoMode () .

n , - rue,
n ,

False, n Cancel,

<Esc>

n . :

s, ok = QtGui. QinputDialog. getText (window,

" ",

" ",
tt=" ")

if ok:
print("Beeo

:",

s)

n .

27 .4.3.

27.5.

27.5.

JJ)I n getint ()

get Integer ().

622

11.

:
< >, < n>[, va1ue=O] [,
min=-2147483647] [, max=2147483647] [, step=1] [, flags=O])
getinteger(<Poe>, < >, < n>[, va1ue=O] [,
min=-2147483647] [, max=2147483647] [, step=1] [, f1ags=0])
gtint(<>,

<>

None.

,
, .

va1ue
min , max-
step- . flags .

.
,

(<>,

<>). n1

, -
,

Fa1se,

Cancel,

True,

<Esc>

. :

n, ok = QtGui.QinputDia1og.getint(window,

" ",

" ",

va1ue=50, min=O, max=100, step=2)


i f ok:

print

("

:",

n).

27 .4.4.

27.6.

27.6.

getDou1e (). :
< >, < >[, va1u~=O] [,
min=-2147483647] [, max=2147483647] [, decima1s=1] [, f1ags=O])

gtDu1(<>,

<>

None.

, .

va1ue
min , max-
decima1s- . flags

.,

. :

(<>,

<>). ,

rue, ,
\,

<Esc>

Fa1se,

27.

623

n, ok =

QtGui.QinputDialog.getDoule(window,
"

" ",

",

value=SO.O, min=O.O, max=lOO.O,


decimals=2)
if ok:

print ("

:",

n)

27.4.5.

get Item ().

:
gt!tm(<>,

<

< >[,

>,

< >,

current=O] [,

editae=True]

[, flags=O])

<>

None.

,
, .

current

, . editae rue,
.

flags

: (<>,

<>).

, - rue,

<Esc>

False, Cancel,

. :

s, ok =

QtGui.QiputDialog.getitem(widow,

" ",
curret=l,

["

1",

" ",

"

2",

"

3"],

editae=False)

i f ok:
prit (" :",

s)

27 .5.

27.7.

27.7.

QFileDialog

QFileDialog .
QFileDialog :

(QObject,

QPaitDevice)

- QWidget - QDialog - QFileDialog

624

11.

QFileDia1og:

<>

QFi1eDia1og(<Poe>,

<>=

QFi1eDia1og([parent=None] [, caption=QString()] [,
directory=QString()] [, fi1ter=QString()])

<>

<

>)

parent ,

, .

<

> (. .

20.2). caption
directory- ,
fi1ter- (, "Images
(*.png *.jpg)").

_ () .
QDialog:

Accepted

27 .5.1.

Rej ected.

QFi1eDia1og

( ;
):

setAcceptMode (<>) - .
QFileDia1og:

AcceptOpen- - ( );

AcceptSave- 1 -

setViewode (<>) _:_ .


Detai1 -

List -

;
;

1-

setFi1eMode (<>) -

r .

AnyFi1e-

ExistingFile-

Directory-

QFileDialog:

QFi1eDia1og:

, _ ;

1-

2-

ExistingFiles-

3-

<Ctrl>;

setOption (<> [, on=True]) - True,


, Fa1se-

QFi1eDia1og ( ;
):

ShowDirsOn1y- .
Directory;
DcntConfirrnOverwrite- ,
;

27.

625

ReadOnly-

HideNameFilterDetails- ;

setOptions (<n>) -

setReadOnly(<a>)- True,

setNameFilterDetailsVisie (<>)

setDirectory () - . :

False, ;

setDirectory(<y>)

setDirectory(<QDir>)

+
+

QDir )' ;

directory () -

setNameFilter(<p>)- .
, . :

dialog.setNameFilter("All (*);;Images (*.png *.jpg)")

setNameFilters (< >) - :


dialog .setNameFilters ( ["All (*) ", "Images (* .png *. jpg) "])

+
+
+

selectFile (< >) - ;


selectedFiles () - ;
setDefaultSuffix(<Pacpee>)- ,
;

setHistory (<>)

setSidebarurls (< QUrl>) - URL-apeco,

- ;

. :

dialog. setSidebarUrls ( (QtCore .QUrl. fromLocalFile (":\ \book") ,


QtCore.QUrl.fromLocalFile("C:\\book\\eclipse")])

setLabelText (< >, <>) - .


QFileDialog:

Lookrn-

FileName- 1 - ;

FileType -

Accept- - , (

- ;

2-

Open

Reject- 4

Save);

, (

Cancel);

savestate () - QByteArray ;

restoreState (<QByteArray>) -

QFileDialog :

currentChanged (const QString&) - .


;

626

directoryEntered(const

11.

QString&}- .

filterSelected (const QString&} - .


;

fileSelected(const QString&}- .
;

filesSelected ( const QStringList&} -

n . n n .

27 .5.2.
QFileDialog
, . n

getExistingDirectory (}. :

getExistingDirectory([parent=None] [, caption=QString(}] [,
directory=QString(}] [, options=ShowDirsOnly])
parent None.
n

directory , n options-

n (. setOption () .

27.5.1).

. :

dir = QtGui.QFileDialog.getExistingDirectory(parent=window,
directory=QtCore.QDir.currentPath()}
n .

27.8.

ltJ 'iW
iJ ...

-'I ~ (:)

tfJ 9

~ (:)

ltJ ....,

~ (F:)

-'I ~ (D:)

~ (G:)
<! ~ D't'D-RW ~s (:)
;; ...., ~ (1:)
(ti

(t)

27.8.

27.

27 .5.3.

627

getOpenFileName ().

getOpenFileName([parent=None] [, caption=QString()] [,
directory=QString()] [, filter=QString()] [,
option~=O])

parent rr None.
caption , directory-
, filter- , options- (.
setOption () . 27.5.1). .

f = QtGui.QFileDialog.getOpenFileName(parent=window,
tin=" ", directory=QtCore.QDir.currentPath(),
filter="All (*);;Images (*.png *.jpg)")
.

27.9.

27.9.

getOpenFileNameAndFilter ().

getOpenFile~ameAndFilter([parent=None]

[, caption=QString()] [,
directory=QString()] [, filter=QString()] [,
initialFilter=QString()] [, options=O])

initialFilter .

, - .

628

11.

f, filter = QtGuioQFileDialogogetOpenFileNameAndFilter(
parent=window,
caption="ao.rtooJ<: J<:", directory=QtCoreoQDir.currentPath(),
filter="All (*);; Images (* opng *. jpg) ",
initialFilter.="Images (* opng. * ojpg) ")

getOpenFileNames ().

:r

getOpenFileNames([parent=None] [, caption=QString()] [,
directory=QString()] [, filter=QString()] [, options=O])
. :

arr = QtGuioQFileDialogogetOpenFileNames(parent=window,
tin="J<: J<:", directory=QtCore.QDir.currentPath(),
filter="All (*);;Images (*opng *ojpg)")
,

getOpenFileNamesAndFilter ().

getOpenFileNamesAndFilter([parent=None] [, caption=QString()] [,
directory=QString()J [, filter=QString()J [,
initialFilter=QString()] [, options=O])

initialFilter .

.
, - .

27 .5.4.

getSaveFileName ()

getSaveFileName([parent=None] [, caption=QString()] [,
directory=QString()] [, filter=QString()J [, options=O])

parent None.
caption , direc;tory- :r
, filter- , options- (.
setOption () . 27.5. 1). .

f = QtGuioQFileDialogogetSaveFileName(parent=window,
tin="J<: ~<:", directory=QtCoreoQDirocurrentPath(),
filter="All (*);;Images (*opng *ojpg)")
.

getSaveFileNameAndFilter ()

27.10.

getSaveFileNameAndFilter([parent=None] [, caption=QString()] [,
directory=QString()] [, filter=QString()] [,
initialFilter=QString()J [, options=O])

27.

629

. 27.1 .

initialFilter .

, - . :

f, filter_ = QtGui.QFileDialog.getSaveFileNameAndFilter(
parent=window,
tin=" ", directory=QtCore.QDir.currentPath(),
filter="All (*) ; ; Images ( *. png *. jpg) ",
initialFilter="Images (* .png * .jpg) ")

27 .6.
(.

QColorDialog.

27.11)

getColor ()

getColor([initial=white] [, parent=None])
getCol~r(<QColor>, <>, <r >[, options=O])
<> parent
None. initial <QColor> . options
( ) QColorDialog:

+
+
+

ShowAlphaChannel- -;
NoButtons- Cancel ;
DontUseNativeDialog.

QColor. Cancel,

630

27.11.

11.

color = QtGui.QColorDialog.getColor(QtGui.QColor("#ffOOOO"},
window, " ", QtGui.QColorDialog.ShowAlphaChannel}
if color.isValid(}:
print(color.red(}, color.green(}, color.lue(}, color.alpha(}}
n -

getRgba (}

QColorD~alog. :

getRgba([initial=4294967295] [, parent=None]}
1\

initial

:t .

True,

(<>,

<>}.

. :

(n, ok} = QtGui.QColorDialog.getRgba(


initial=QtGui .QColor ( "#ffOOOO"} . rgba (}, parent=window}
i f ok:
color = QtGui.QColor.fromRgba(n}
print(color.red(}, color.green(}, color.lue(}, color.alpha(}}

27.7.

QFontDialog.

1 :

getFont([parent=None]}
getFont(<QFont>[, parent=None]}

getFont (}

27.

631

getFont(<QFont>,
getFont(<QFont>,

<>,

<

<>,

< >,

>)

<>)

<> parent
None. <QFont> . <>
NoButtons DontUseNativeDialog QFontDialog.
: (<QFont>, <>). True,
QFont .
:

(font,, ok) =

QtGui.QFontDialog.getFont(QtGui.~Font("Tahoma",

window,

16),

" ")

if ok:

print(font.family(), font.pointSize(), font.weight(),


font.italic(), font.underline())
.

27.8.

27.12.

27.12.

Q~rroressage u
(.

27.13).

, . ,
. QErroressage :

(QObject, QPaintDevice) - QWidget - QDialog - QErrorMessage



<>=

QErrorMessage:

QErrorMessage([parent=None])

632

'-i)

11.

L oom-oo-..
,. ~~~ . . . .

27.13.

.....

. ..

. - - ....-.... .... ]

n~r

showMessage (< >).


showMessage (const QString&) .

27.9.

QProgressDialog u

Ca ncel ( . 27.14).

11

QProgressDialog :

(QObject , QPaintDeviceJ - QWidget - QDialog - QProgressDialog


QProgressDialog:
<>=

QProgressDialog([parent=None] [, flags=OJJ

<> ~ QProgressDialog(<Tec > ,


<

parent~None]

Cancel> ,
[ , flags=O))

<> ,

<>[ ,

parent ,
u , .

flags n (. . 20.2).
QProgressDialog
( ; n n 1
u):

+
+
+
+

setLabel (<QLabel>J - n;
setBar (<QProgressBar >J - n ;
setCancelBu t t o n (<QPushButton>) - ;
setValue ( < > J - .

11'1

processEvents ( J . setValue ( int J;

m1111 nu

fiiiiiiiiiiiiiiiil
.

27.14.

J ~s:ot.

t
t

27.

633

value () - ;
setLabelText (< >) .

setCancelButtonText (<

Cancel.

setLabelText (const QString&);

Cancel>) -

setCancelButtonext (const

QString&);

setRange (<>,

<>), setMinimum (<>)

setMaximum (<>) -

. ,
,

setMaximum()

setMinimumDuration (<>) -

setMinimum(int)

setMinimum ()

setMaximum(int);

( 4000).

setMinimumDuration(int);

t
t
t

reset () - . ;
cancel () - Cancel. ;
setAutoClose (<>) - True,
;

setAutoReset (<>) - . True, ;

wascanceled () - True, \.

QPgressDialog canceled (),

Cancel.

27.1 .

QWizard QWizardPage ,
( )

Back

()

Next

(). QWizard ,

27.1 0.1.

QWizardPage.

QWizard

QWizard ,
. QWizard :

(QObject, QPaintDevice) - QWidget - QDialog - QWizard


QWizard:
<>=

QWizard([parent=None] [, flags=O])

QWizard
( ;
):

634

11.

addPage (<QWizardPage>) - . QWizardPage;

+
+
+

setPage (<!'!>, <QWizardPage>) - ;


removePage (<>) - ;
page (<>)

QWizardPage), , None,
;

+
+
+

pageids () - ;

setStart Id ( <11>) - ;

+
+

startld () - ;

current Id () -

curr~ntPage ()

QWizardPage) None, ;

visi tedPages () ;

hasVisitedPage (<>) - True,


'
False - ;

+
+
+
+

back () - 1\ Back. ;
next () - Next. ;
restart () -

. ;

nextrd (self) ,
QWizarcl. . i

Next.

-1;

initializePage (self, <>) - ,


QWizarcl.
, .

Next

IndependentPages,

cleanupPage (self,

<>) -

QWizard,

Back

Back.

IndependentPages,

validateCurrentPage (self) - ,
QWizard, ,
.

Next

Finish.

True, , False- .
False, ;

setField (<>,

<>)

registerField ()

27.

635

QWizardPage. n t n,
;

fie1d (<>) -

registerFie1d () QWizardPage.
,
;

setWizardSty1e (<>) - .
QWizard:

C1assicSty1e-

ModernSty1e- 1;

MacSty1e- 2;

Aerosty1e- 3 - Windows Vista.


ModernSty1e;

setTit1eFormat (<>) - .
QtCore. Qt:
- ;

P1ainText -

RichText -

1 - ;

Autoext -

2-

( ).

RichText,

P1ainText;

setSuTit1eFormat (<>) -

setButton(<Po>,

setTit1eFormat ();

<QAstractButton>)- .

QWizard:

BackButton- - Back;

NextButton- 1 - Next;

ComrnitButton- 2 - Commit;

Finishutton-

Cance1Button- 4 - Cancei ( NoCance1Button,

3 - Finish;

);

He1pButton- 5 - Help ( ,
HaveHe1pButton);

Customutton1- - ( ,
HaveCustomutton1);

customutton2- 7 - ( ,
. HaveCustomutton2);

customutton3- 8 - ( ,
Havecustomutton3);

button (<>) -

t setButtonText (<>,

<

11.

n>)- n

t buttonText (<>)

- n ;

t setButtonLayout (<

>) - n n.

n n. n

Stretch

setPixmap(<Po>,

QWizard,

. n

<QPixmap>)-

watermarkPixmap-

- ,

n n

ClassicStyle

Modernstyle;

, n

LogoPixmap- 1 -

QWizard:

ClassicStyle

ModernStyle;

BannerPixmap- 2 -

, n

ModernStyle;

ackgroundPixmap-

3 -

t setOption (<> [, on=True J ) -

n n

MacStyle;

True,

n , n n,

False,

n. n

QWizard:

IndependentPages- . n ,
ini tializePage () ,
cleanupPage () ;

IgnoreSuTitles- n ;

ExtendedWatermarkPixmap-

WatermarkPixmap

n ;

NoDefaul tButton-

NoBackButtonOnStartPage-

NoBackButtonOnLastpage-

Next

Finish

DisaedBackButtonOnLastPage

_ ;

Back

Back

Back

HaveNextButtonOnLastPage-

Next

HaveFinishButtonOnEarlyPages-

Finish

NoCancelButton-

CancelButtonOnLeft-

Cancel;

Cancel

Next

Back

( -

Finish);

Help;

HaveHelpButton-

HelpButtonOnRight-

avecustomuttonl- customuttonl;

Help

637

HaveCustomutton2- Customutton2;

HaveCustomutton- Customutton;

setOptions (<>) - .

27.

QWizard :

currentidChanged(int)- .
;

customuttonClicked(int)- Customuttonl,
Customutton2 Customutton;

+
+
+

helpRequested () -

pageRemoved ( int) -

Help;

pageAdded ( int) -

27.1 0.2.

QWizardPage

QWizardPage .
QWizardPage :

(QObject, QPaintDevice) - QWidget - QWizardPage



<>

QWizardPage:

= QWizardPage ( [parent=NoneJ.)

QWizardPage ~1

( ;
):

wizard () - ( QWizard) None, ;

+
+
+
+
+

setTitle (<>) - ;
ti tle () - ;
setSuTitle (<>)- ;

subTitle () - ;
setButtonText (<>,

<

>)-

( <> .

setButton () QWizard);

+
+

buttonext (<>) - ;

setPixmap (<>,

<QPixmap>) - (
setPixmap () QWizard);

<> .

registerrield () - ,
. :

<QWidget>[, property=None] [,
changedSignal=O] )

registerF'ield(<Coco>,

<> ~ .

*,

638

11.

(, - ),

Finish

Next

. .

setField (),

field ().

property
, changedSignal-'- , .

setDefaultProperty(<Haae

>,

property,

changedSignal)

QWizard.

:
n:

'l':

QAstractButton

checked
value
currentindex.
dateTime
text
currentRow
value

toggled ()
valueChanged ()
currentindexChanged()
dateTimeChanged()
textChanged ()
currentRowChanged()
valueChanged ()

QAstractSlider
QComoBox

QDateTimeEdit
QLineEdit
QListWidget
QSpinBox

setField (<>,

<>)

,
;

field (<>) -

,
;

setFinalPage (<>) - ~ True,


Finish;

isFinalPage () - True,
Finish, False- ;

setCommi tPage (<>) -

isCommitPage ()

Commit,

True,

Commit;

True,
False- ;

isComplete (self) - , ,

Finish

Next

( rue) (

False). ,

QWizardPage, .
completeChanged ();

nextid (self) ,
QWizardPage, .

initializePage (self) -

Next.

-1;
,

QWi zardPage,
, .

Next

, .

27.

639

n IndependentPages, n n
;

cleanupPage (self) - nn ,
QWizardPage, n Back.
n n

Back

, n

. n

IndependentPages, ;

validatePage (self) - nn ,
QWizardPage, n n ,
. n n

Next

True, , False False, n

Finish.

n .
n.

28

PyQt

SDI-

DI-

n n :

SDI-npuoeu

(Single Document lnterface)-

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

WordPad

Paint

Windows.

SDI-n, n n

setCentralWidget ()

D/-u

QainWindow;

(Multiple Document lnterface)-

. n
n DI-n n

Photoshop,

. DI-n,
n n

QMdiArea

setCentralWidget () QMainWindow. DI-


n QdiSuWindow.

28.1.

QMainWindow n, , n
, nn n, n .

QMainWindow

(QObject, QPaintDevice) - QWidget - QMainWindow


QMainWindow :
<>= QainWindow([parent=<Poe>]

[,

flags=<T >])

n parent .
n flags, .

20.2.

QMainWindow n
(n ; n n

):

setcentralWidget (<QWidget>) -

n n

centralWidget () -

n None,

n ;

28.

SDI-

D/-

641

menuar () - ( QMenuBar);

menuWidget () -

( QWidget);

setMenuBar (<QMenuBar>) -

setMenuWidget (<QWidget>) - ;

createPopupMenu () - ,
,

( QMenu).
, .
n ;

statusBar () - ( QStatusBar) ;

setStatusBar (<QStatusBar>) -

addToo1Bar () - n . :

n ;

addToo1Bar(<QToo1Bar>)
dd1r(<>,
dd1r(<

<Qoo1Bar>)
n>)

.
n . <>

QtCore. Qt: LeftToo1BarArea (),


RightToo1BarArea (), TopToo1BarArea () ottomToo1BarArea ().

n ,
(

insertToo1Bar ( <Qoo1Bar 1>,


1>;

<QToo1Bar 2>) -

QToo1Bar);

n <QToo1Bar

2> n

n <Qoo1Bar

removeoo1Bar(<QToo1Bar>)- n .

toolBarArea ( <QToo1Bar>) -

LeftToo1BarArea (), RightToo1BarArea (n),

TopToo1BarArea (), BottomToo1BarArea () NoToo1BarArea (n


n) QtCore.Qt;

+
+
21

setToo1ButtonSty1e (<>) - n .
n QtCore.Qt:

Too1ButtoniconOn1y- - ;

Too1ButtonTextOn1y- 1 - ;

ToolButtonTextBesideicon- 2 - ;

Too1ButtonTextUndericon- - ;

oo1ButtonFo11owSty1e-

4 -

n ;

toolButtonSty1e () - ;
seticonSize (<QSize>) - ;

1349

642

11.

iconSize () - ( QSize);

setAnimated(<a>)- True (
),
.

setAnimated (bool);

addToolBarBreak ( [area=TopToolBarArea]) -

.
.
;

insertToolBarBreak(<QoolBar>)- .
;

removeoolBarBreak

toolBarBreak ( <QoolBar>) -

( <QToolBar>) - ;
rue.

False-

addDockWidget () - ~. :
addDockWidget(<Oac>,
addDockWidget(<OCac>,

<QDockWidget>)
<QDockWidget>,

<>)

.
<> QtCore. Qt:
LeftDockWidgetArea (), RightDockWidgetArea (), TopDockWidgetArea ()
BottomDockWidgetArea ().
. <>

QtCore.Qt: Horizontal vertical.

Horizontal,
Vertical- ;

removeDockWidget (<QDockWidget>) -,- .


;

dockWidgetArea (<QDockWidget>) -

LeftDockWidgetArea (),
RightDockWidgetArea (),
TopDockWidgetArea (), BottomDockWidgetArea () NoDockWidgetArea (
) QtCore. Qt;

setDockOptions (<>) - .
: AnimatedDocks 1 AllowabbedDocks.
( 1) QMainWindow:

AnimatedDocks- ,
;

AllowNestedDocks- , (
) , ~ ;

AllowabbedDocks- ,

. .

;

ForceTabbedDocks- ,
AllowNestedDocks ;

28.

SDI-

643

D/-

VerticalTabs-,-- ,
( , ,
, , , ,
, ). ,

. AllowabbedDocks
.

0
i .

+
+

AnimatedDocks

VerticalTabs.

dockOptions () - Jl ~ ;
setDockNest:ingEnaed(<iJ>)- rue,

AllowNestedDocks, False- .

isDockNestingEnaed
,

() False--:

setDockNest ingEnaled (bool);

True, AllowNestedDocks

setTabPosition (<>,

<>)

.
. <>

North -

-;

South -

1-

west -

East -

3-

QTabWidget:

-;
;

tabPosition (<>) -

+
+

setTabShape (<>)- .
QTabWidget:

Rounded- - ( );

Triangular- 1 - ;

tabShape () - ;
setCorner (<>,

<>)

. ,
. <>
QtCore.Qt: LeftDockWidgetArea (), RightDockWidgetArea (
), TopDockWidgetArea () BottomDockWidgetArea (). <>

QtCore. Qt:

TopLeftCorner- ;

TopRightCorner- ;

BottomLeftCorner- ;

BottomRightCorner- ij _;

corner (<>) - , ~ ;

644

sp1itDockWidget () -

11.

, <QDockWidget

1>,

<QDockWidget 1> , <QDockWidget 2>-

. <>.

<.> QtCore. Qt:


Horizonta1 Vertica1. Horizonta1, <QDockWidget 2>
, Vertica1- . <QDockWidget

1>

, <QDockWidget 2> ,
. :

sp1itDockWidget(<QDockWidget 1>, <QDockWidget 2>,

taifyDockWidget (<QDockWidget

<QDockWidget

1>,

<>)

<QDockWidget

2> <QDockWidget

2>) -

1>, , ,

taifiedDockWidgets (<QDockWidget>) -

QDockWidget), ,
;

saveState ( [version=O]) -

QByteArray

(,

),

restoreState(<QByteArray>[, version=O]).
,

setObjectName (< >) QObject. :


self.dw = QtGui.QDockWidget("MyDockWidget1")
se1f .dw. setObjectName ( "MyDockWidgetl")
, saveGeometry ()

QWidget. QByteArray .

restoreGeometry(<QByteArray>);

restoreDockWidget (<QDockWidget>) -

restoreState (). True,


,

28.2.

Fa1se-

,
, .
( QMenuBar),
( QMenu) .
( QAction),
, . ,
, .

.
QMenu
contextMenuEvent () _ (),

28.

28.2.1.

SD/-

645

D/-

QMenuBar

QMenuar .
.

menuBar ()

QMainWindow.

setMenuBar ( <QMenuBar>). QenuBar :


(QObject, QPaintDevice) -

QWidget -

QMenuBar

QMenuar :
<>= QenuBar([parent=<Poe>])

QMenuar
( ;

u):

addenu ( <Qenu>) -

QAct ion,

, , ( setVisie ())

( setEnaed () );

addenu ( [ <Qicon>,

J <>) -

( QMenu). <>
&, u, u
. &, ,

<Ait>

. &, ;

insertMenu (<QAction>,

<Qenu>) - <Qenu> <QAction>.

QAction;

addAction () - . :
addAction(<QAction>)
addAction(<Haae>)

+
+
+

<>,

addAction(<Haae>,

<>)

<>)

-> QAction
-> QAction

clear () - ;
setActiveAction (<QAction>) - ;
activeAction ()

-> QAction

addAction(<Haae>,

( QAction)

None;

setDefaultUp (<>) -

True,

, ;

setVisile(<a>) ~ False,

. True .
QMenuBar :

hovered(QAction

*) -

QAction;

triggered (QAction *) -

QAction.

646

28.2.2.

QMenu

11.

QMenu

, ,

(QObject, QPaintDevice) - QWidget -

QMenu

Qenu

Qenu:
<>= Qenu([parent=None])
<>= Qnu(<>[,

parent

parent=None])

<> &, ,
. , &,
, .

<Ait>

. &,

QMenu

( ;
):

addAction () - . :
addAction(<QAction>)
-> QAction
-> QAction
addAction(<Haae>, <>, <>[, shortcut=O])
-> QAction
addAction(<Haae>, <>[, <shortcut>])
-> QAction
addAction(<Qicon>, <>, <>, <>[, shortcut=O])
-> QAction
addActi~n(<Qicon>, <>, <>[, <shortcut>])
-> QAction
addAction(<Haae>)

addAction(<Qicon>,

<>)

<> &, ,
. ,
&, , .

<Ait>

&, .

, , ,
.

shortcut "" ,

. ""
, .

shortcut:
QtGui .QKeySequence ( "Ctrl+R")
QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_R))
QtGui .QKeySequence. fromString ("Ctrl+R")

addActions (<n
;

QAction>)

QWidget:

28.

647

D/-

SDI-

insertAction (<QAction 1>,


<QAction 1>;

<QAction 2>) -

<QAction 2>

<:

insertActions (<QAction>,

QAction>) -
<QAction>;

- (

actions ()

removeAction (<QAction>)

QAction);

- ;

addSeparator () QAction;

insertSeparator (<QAction>) -
QAction;

addenu ( <Qenu>) -

addenu

( [<Qicon>, ] <>) -

QAction;

QMenu);

insertMenu(<QAction>, .<QMenu>)- <Qenu>


<QAction>. QAction;

c1ear ()

isEmpty () -
Fa1se- ;

menuAction () -

- ;
rue, ,

QAction),

. (
setVisile ()) ( setEnaled

setT i t1e (<>)

ti t1e () -

seticon (<Qicon>)

icon ()

setActiveAction (<QAction>)

acti veAction () None;

setDe_fau1tAction ( <QAction>)

( l );

- ;

;
- ;

- (

Qicon);

- ;

QAction)

- _ ;

defau1tAction () None;

QAction)

setTearOffEnaed(<a>)--

True,

(
, );

isTearOffEnaed

Fa1se--

() -

True,

isTearOffenuVisile

() - rue,
Fa1se-- ;

hideTearOffenu

()

- ;

648

11.

setSeparatorsCollapsie (<>) True,


, ,

. , , , ;

popup ( <QPoint> [,

<QAction>] ) -

. , ,
;

_ ( [ <QPoint> [,

<QAction>]]) -

QAction ( )
None ( , ,

<Esc>).

, ,
.

_ ().

QAction ( ) None ( ,
,
_(<

<Esc> ).

_(<

QAction>, <QPoint>[, <QAction>})


QAction>, <QPoint>, <QAction>,

<QWidget>)

<QAction>, ,
<QWidget>

.
.

QMenu :

hovered (QAction

*) -

triggered (QAction *) -

_OAction;

aboutoshow () -

aboutToHide () - .

28.2.3.

QAction;

contextMenuEvent (self, <event>).


.
<event> QContextMenuEvent,
. QContextenuEvent
:

(J ( J -

pos () -

QPoint

globalX() globalY()-
;

globalPos () - QPoint .

28.

SDI-

649

D/-

contextMenuEvent ().
() globalPos ().

def contextMenuEvent(self, event):


self.context_menu.exec_(event.globalPos())

context _ menu. ,
contextMenuEvent (! .

28.2.4.

QAction

QAction , ,

- .
. ,
, .

QAction :

QObject - QAction

<>

QAction:

QAction(<QObject>)

<>

Qtin(<>,

<>

QAction(<Qicon>,

<QObject>)
<QObject>)

<>,

<QObject> ' None.


<.> &, ,
. ,
&, , .

<Ait>

&, .

<Qicon> .

QAction ( ;
):

setText (<>) - . <>


&, ,
. ,
, , ;

+
+
+
+

text () -

seticon (<Qicon>) - ;
icon () - ( Qicon);
seticonVisieinenu (<>) - F'alse,
11 ;

setSeparator (<>) -

't rue,

isSeparator () True, ,
False - ;

650

11.

setShortcut (<QKeySequence>) - "" .


"" , ~
. :

"Ctrl+O"
QtGui .QKeySequence ( "Ctrl+O")
QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_O))
QtGui.QKeySequence.fromString("Ctrl+O")
QtGui.QKeySequence.Open

setShortcuts () -

""

:
setShortcuts(<Cnco n

QKeySequence>)

setShortcuts(<Caapa >)

< >

StandardKey QKeySequence (, Open, Close, , Cut . .;


QKeySequence);

setShortcutContext (<>) - ""


. QtCore. Qt:

WidgetShortcut- - ,
;

WidgetWi thChildrenShortcut- 3 - ,
;

WindowShortcut- 1 - , ,
, ;

ApplicationShortcut- 2 - , ;

+
+
+
+
+

setool ip (<>) - ;

tool Tip ()

- ;

setWhatsThis (<>) - ;
whatsThis () - ;
setStatusTip (<'f'>) - , ,
;

+
+

statusTip () - ;
setCheckae (<>) -

True,

, -
;

isCheckale () False-

'rue, ,

setChecked (<>) -

True, .

_ .

isChecked () -

setChecked (bool);

False-

True, -
;

28.

SDI-

setDisaed (<>)

651

D/-
n

True,

n. False n.
setDisaed

setEnaed (<>) -

(bool);

n False,

n. rue n.
setEnaed

isEnaed

() -

(bool);

True, n, False- n

setVisie (<>) - n

False,

. rue n.
setVisie

isVisie

() -

(bool);

False, , True- n

setMenu ( <QMenu>) - ;

menu () - (n QMenu)
None, ;

. setFont (<QFont>) - ;

font () - n QFont ;
setAutoRepeat (<>) - n rue (
), n, n
"" ;

setPriority(<pope>)- n . n

LowPriority (), NonalPriority () HighPriority


() QAction;

priority () - n ;
setData (<>) -n n n
;

data () - n , n
setData (), None;

setActionGroup ( <QActionGroup>) - n;

actionGroup () None;

n (n QActionGroup)

showStatusText ( [ <QWidget>=None J)

QEvent. StatusTip -

n rue, n n.
, n nn

event (self, <event>). QEvent. statusTip n <event> n


n QStatusTipEv~nt.
tip () . ,
QLabel:
def event(self, ):
if e.typ~() == QtCore.QEvent.StatusTip:
self.setText(a.tip())
return True
return QtGui.QLabel.event(self, )

652

+
+

1/.

hover () - hovered (). ;


toggle () -

. -

trigger () - triggered (). .

+
+
+

QAction :

changed () -

hovered () - ;
toggled (bool) -

triggered (bool=O) - ,
, trigger ().

28.2.5.
QActionGroup .
.
, .

QActionGroup :

QObject - QActionGroup
QActionGroup :
<>

= QActionGroup(<QObject>)

<QObject> None.

. .

QActionGroup :

addAction () - .
QAction. :
addAction(<QAction>)
addAction(<Haae>)

addAction(<Qicon>,

+
+

<>)

removeAction (<QAction>) - ;
actions () -

QAction,

, ;.

checkedAction () -

( QAction)

None;

setExclusive (<>) - True (


), .
, <

. False .

'

setExclusive (bool);

28.

SDI-

setDis.aed (<>)

D/-

653

True,

. False
.

setEnaed (<>)

set Disaed (bool) ;

False,
True

. setEnaed (bo~l);

isEnaed

() -

rue, ,

False-

setVisie (<>) -

False,
True .
setVisie (bool);

isVisie

() - False, , True-

QActionGroup :

hovered (QAction

*) -

. .
(

QAction);

selected (QAction *) -

, .
( QAction);

triggered (QAct ion *) -

, .
( QAction).

28.3.

addToolBar {)

insertToolBar () QainWindow. addToolBar {)

, .


. , ,

setAllowedAreas () QToolBar,
().

setFloatae

28.3.1.

QToo/Bar

QToolBar ,
. QToolBar :

(QObject, QPaintDevice) - QWidget -

QoolBar

QoolBar:
<>= Qlr([rnt=<>])
<>= Qlr{<>[,

rnt=<>])

parent , <

> , , -

654

11.

, t:

.
.

QToolar

l ( ;
):

addAction () - . :
addAction(<QAction>)
addAction(<Haae>)

addAction(<Qicon>,

<>)

addAction(<Haae>,

<>,

addAction(<Haae>,

<>)

addAction(<Qicon>,
addAction(<Qicon>,

<>)

<>,

<>,

<>,

<~>)

<>)

->
->
->
->
->
->

QAction
QAction
QAction
QAction
QAction
QAction

QWidget:

addActions (< QAction>) -


;

insertAction(<QAction 1>, <QAction 2>)- <QAction 2>


<QAction 1>;

insertActions (<QAction>,

<

QAction>) -

+
+

actions () - ( QAction);

removeAction (<QAction>) -

. ;

addSeparator () - QAction;
insertseparator ( <QAction>)

addWidget (<QWidget>) -

QAction;

, ,

<QAction>;

QAction;

inser_tWidget (<QAction>, <QWidget>) -


QAction;

.r

widgetForAction (<QAction>) -

+
+

clear () - ;
setAllowedAreas (<>) -

. (

1)

LeftToolBarArea (), RightToolBarArea (), TopToolBarArea (

), BottomToolBarArea () AllToolBarAreas QtCore.Qt;

setMovae (<>)

True (
False

), .
;

isMovae
,

() - rue,
False- ;

28.

SDI-

/-

655

setF'loatae (<>) - True (


), ,

F'alse,

isF'loatae () ,

isF'loating ()

rue,

F'alse-

F'alse-

rue, ,

setToolButtonStyle (<>) -

setoolButtonstyle

(Qt: :ToolButtonStyle).
QtCore. Qt:

TooluttoniconOnly- - ;

TooluttonTextOnly- l - ;

oolButtonTextBesideicon- 2 - ;

ToolButtonTextUndericon- 3 - ;

ToolButtonF'ollowStyle- 4 -

+
+

toolButtonStyle () - ;

+
+

iconSize () - ( QSize);

seticonSize (<QSize>) - .
seticonSize(const QSize&);

toggleViewAction () -

QAction), -

QToolBar ( ;
):

actionTriggered (QAction *) -

QAction;

visiili tyChanged (bool) -

rue, , F'alse ;

topLevelChanged(bool)- .
rue,
, F'alse- .

28.3.2. accQToo/Button
,

QToolButton.

widgetF'orAction(<;QAction>)

QToolar.

QoolButton :

(QObject, QPaintDevice) - QWidget

QAstractButton

QoolButton

QToolButton :

<>= QToolButton([parent=<Poe>])

656

11.

QToolutton n
(n ; n n
):

setDefaultAction ( <QAction>) - n.
setDefaultAction (QAction *);

defaultAction () -

(n QAction),

n;

setoolButtonStyle (<>) - n.

setToolButtonstyle (Qt: :ToolButtonStyle).

<> . .

+
+
+
+
+

28.3.1 n setToolButtonStyle ();

toolButtonStyle () - n;
setMenu ( <QMenu>) - ;
menu () - (n Qenu) None;
showenu () - , n. ;

setPopupMode (<>) - n .
n QToolutton:

DelayedPopup- - n n
n ;

enuuttonPopup- 1 - n n n , ~
n ;

InstantPopup- 2 - n n .
triggered () n ;

+
+

popupMode () - n ;
setArrowType (< >) -

, n. n

LeftArrow

RightArrow

NoArrow (
QtCore. Qt;

),

UpArrow,

DownArrow,

setAutoRaise (<>) - n False, n


. n , n
n.

QToolutton triggered (QAction *), n

n , n n .
n n n QAction.

28.4.

n n

, (n, n),
n

nn n.

n n n

QDockWidget. QDockWidget :

(QObject, QPaintDevice) - QWidget - QDockWidget

28.

/-

SDI-

657

QDockWidget:

<>

QDockWidget([parent=<Poe>]

<>

QDockWidget(<Haae>[,

[,

flags=<T >])

rnt=<>]

[,

flags=<T >])

<> ,
, ,
.
.

QDockWidget

( ;
):

setWidget (<QWidget>) - ,
;

+
+

widget () - , ;
setTitleBarWidget (<QWidget>) -

n;

ti tleBarWidget () -

, None, J-J;

setAllowedAreas (<>) -

, .

1)

LeftDockWidgetArea (), RightDockWidgetArea (), TopDockWidgetArea (),


BottomDockWidgetArea () AllDockWidgetAreas QtCore .Qt;

setFloating (<>)- True,


, False,
- ;

isFloating () - rue, ,
False- ;

setFeatures (<>)- .
(

DockWidgetClosable-

DockWidgetMovable-

1)

QDockWidget:

n ;

DockWidgetFloatable- ;
DockWidgetVerticalTitleBar- ,
;

NoDockWidgetFeatures- n ,
;

+
+

features () - ;
toggleViewAction () -

( QAction),

n.
QoockWidget ( ;
):

658

11.

dockLocationChanged (Qt:: DockWidgetArea) -

,
;

visiilityChanged

(bool) -

True, , E'alse ;

topLevelChanged (bool) -

True,

, E'alse- .

28.5.

QStatusBar ,

.
, , .
:

. . ,
, ,

setStatusTip (),

.
showessage

();

.
. ,

addWidget () insertWidget ( J.
;

.
. ,

addPermanentWidget ()
insertPermanentWidget ().

, ,

statusBar ()

QainWindow,

setStatusar

QStatusBar

( <QStatusBar>).

(QObject, QPaintDevice) - QWidget - QStatusBar


QStatusBar:
<>= QStatusBar([parent=<Poe>])

QStatusBar
( ;
):

showMessage (<> [, msecs=O] ) -

. , ,
l) clearessage ().

showMessage (const QString&, int = );

\+

28.

SDI-

currentMessage () -

659

D/-

, -

clearMessage () -

addWidget(<QWidget>[,

stretch=O])- n

. n stretch ;

insertWidget (<>,

<QWidget> [, stretch=O]) - n

n n. n stretch
;

addPermanentWidget ( <QWidget> [,

stretch=OJ) -

n . n stretch ;

insertPennanentWidget (<>,

<QWidget> [,

stretch=O]) -

n n n.

stretch ;

removeWidget (<QWidget>) - n n .
, n ,

. n ;

setSizeGripEnaed (<>) -

n True,

n .
False .

QStatusBar messageChanged ( const QString&),


n . n n
n .

28.6.

DI-

DI-n

(Multiple Document lnterface)

. DI-n,
n n

QMdiArea

setCentralWidget () QMainWindow. DI-


n QMdiSuWindow.

28.6.1.

QMdiArea

QMdiArea DI-, n
(n QMdiSuWindow). QMdiArea
:

(QObject, QPaintDevice) - QWidget - QFrame QAstractScrollArea

- QMdiArea

QMdiArea :
<>= QMdiArea([parent=<Poe>])

QMdiArea (n ; n
l n ):

660

addSuWindow ( <QWidget> [,

flags=<Tn >] ) -

11.

n <QWidget> (n
QdiSuWindow). :

w = MyWidget ()
sWindow = self.mdi_area.addSuWindow(w)
sWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)

# ...

sWindow. show ()
n ,

WA_ DeleteOnClose, , show ().


n

<QWidget>

(n QMdiSuWindow). :

w = MyWidget ()
sWindow = QtGui.QdiSuWindow()
self.mdi_area.addSubWindow(sWindow)
sWindow.setAttribute(QtCore.Qt.WA_DeleteOnClose)

# :

sWindow.setWidget(w)
sW indow. show ( )
DI-, DI-
n . :

sWindow =

QtGui.QdiSuWindow(self.mdi_area)

activeSubWindow () - (n
QdiSuWindow) None;

currentSuWindow () - (n
QdiSuWindow) None. n
n activeSuWindow (), DI-
;

subWindowList ( [order=CreationOrder]) -

(n QMdiSuWindow), DI-, n
n. n order QMdiArea:

CreationOrder- - n n n DI
;

StackingOrder- 1 -

n n n n.

n , n
- ;

ActivationHistoryOrder- 2.-

n n n n

. n , n
n;

remov~SubWindow (<QWidget>) - DI-;

setActiveSuWindow(<QMdiSuWindow>)- .

n None, .
setActiveSuWindow (QdiSuWindow *);

28.

SD/-

/-

661

setActivationOrder (<order>) - n n n
activatePreviousSuWindow (), activateNextSuWindow () . n <order>
, n order suWindowList ();

+
+

activationOrder () - n ;
activatePreviousSuWindow()- n .

setActivationOrder();

activateNextSubWindow () - .

setActivationOrder();

+
+
+

closeActi veSuWindow () - . ;
closeAllSuWindows () - . ;
cascadeSuWindows () - , n .
;

tileSuWindows () -

n , n .

setViewMode (<>) -

DI-. n

<> QMdiArea:

+
+

SuWindowView- - ( );

TabbedView- 1 -

viewode () -

n ;

DI-;

setTabPosi tion (<>) - n n


TabbedView.
. n <>
QabWidget:

North-

South- 1 - ;

West -

2-

East -

- ;

;
n;

tabPosition (<>) n n
n TabbedView;

setTabShape (<>) - n
TabbedView. QTabWidget:

Rounded- - ( );

Triangular- 1 - ;

~abShape () -

+
+

TabbedView;

setackground ( <QBrush>) - n DI-;

setOption (<> [, on=True J ) -

n True,

, False- . n <>
DontMaximizeSuWindoWOnActivation QMdiArea.

662

U.

, r-t
;

testOption (<>) - True, ,


False- .

QMdiArea suWindowActivated (QdiSuWindow *),

-r . 11

( QMdiSuWindow)

None.

28.6.2.

QMdiSubWindow .

QMdiSuWindow , DI-.
QMdiSuWindow :

(QObject, QPaintDevice) - QWidget -

QdiSuWindow

QMdiSuWindo;.:
<>= QdiSuWindow([parent=<Poe>]

[,

flags=<T >])

QMdiSuWindow
. ( ;
):

setWidget (<QWidget>) - ;

widget () - ;

mdiArea () - DI- ( QMdiArea)


None;

setSystemenu(<Qenu>)-
;

systemenu ()

( QMenu)

None;

showsystemenu () -

setKeyboardSingleStep(<aee>)-
.
,

Move

Size.

s;

setKeyboardPageStep (<>) -

<Shift>.

- 20;

showShaded () -

, .

isShaded () - True, , False ;

setOpt ion (<> [, on=rue] ) -

True,

False- .

28.

SDI-

663

I-

n <> QMdiSuWindow:

RubberBandResize- n , n
n n, .

RubberBadove- n , n n
n n n, . n
n ;

testOption(<On>)-

False-

True, n ,

n .

QMdiSuWindow 11 :

aboutToActivate () - n ;

windowStateChanged(Qt: :WindowStates,Qt: :WidowStates)- n


. n n n ,
n- .

28.7.

QSystemTrayicon n n ,

n n n

QSystemTrayicon

Windows.

QObject - QSystemTrayicon

QSystemTrayicon:

<>= QSystemTrayicon([parent=<Poe>])

<>=

QSystemTrayicon(<Qicon>[,

rnt=<>])

QSystemTrayicon :

isSystemTrayAvailale

() - True,
False- n . ;

seticon ( <Qicon>) -

. ~

icon () -

setContextMenu (0:::Qenu>) - , n -

contextMenu () - (n QMenu);

setToolTip (<>) - n n;

toolTip () - n n;

(n Qicon);

n n ;

setVisile(<a>)- n rue,
,

False- .

setVisile(bool);

show () - . ;

hide () - . . ;

664

isVisie

() -

1/.

True, , False-

geometry () -

QRect

showessage () -

showMessage(<aooo>,

< >[,

icon=Information] [,

msecs=lOOOO])

icon ,
Noicon, Information, warning
Cri tical QSystemrayicon: msecs

, . ,

, , msecs
;

supportsMessages () - rue,
False- . .

Qsxstemrayrcon :

activated(QSystemTrayicon: :ActivationReason)-
.
QSystemTrayicon:

Unknown -

Context- 1 -

DouleClick-

Trigger-

MiddleClick- 4 -

;
;

2 -

- ;
;

messageClicked () - .

Python

PyQt.

. ,
.

http://www.python.org/

http://www.riverbankcomputing.eo.uk/.

, , .

PyQt
http://qt.nokia.com/ .

http://docs.python.org/

Python,

Qt,

. ;
, , . . ,

Python

Python'

Python

http://pypi.python.org/pypi?%3Aaction=index

http://sourceforge.net/

Python.

PySide (http://www.pyside.org/),
Nokia. PyQt
LGPL.
r .: Tkinter, wxPython (http://www.wxpython.org/),
PyGTK (http://www.pygtk.org/), PyWin32 (http://sourceforge.net/projects/pywin32/)
pyFLTK (http://pyfltk.sourceforge.net/). pygame
(http://www.pygame.org/), , Django
(http://www.djangoproject.com/), W-.

, ,

.
(,

http://www.google.com/)

- n - .

ftp://85.249.45.166/9785977507974.zip.
www.bhv.ru.

F-

. .\.
.1.

Listings.doc

PyQt.doc

750 n ,

Readme.doc

PyQt

@
@abstractmethod 243
@classmethod 242
@staticmethod 242

_abs_() 240
_add_() 239
_all_ 221, 226
_and_() 240
_ annotations_ 215
- bases- 235
_bool_() 238
_call_O 236
_cause_257
_complex_() 239
_conform_() 333
_contains_() 241
_debug_258
_de1_() 232
_de1attr_() 238
_delitem_() 237
_dict_ 213,219,237
_doc_ 34, 35, 79
_enter_() 252, 253
_eq_()241
_exit_() 252,253
file
- 262
_float_() 238
_floordiv_() 240
_ge_()241
_getattr_() 237, 244
_getattribute_() 237, 244
_getitem_ 236
_gt_()241

_hash_() 239
_iadd_() 239
_iand_() 241
_itloordiv_() 240
_ilshift_() 241
_imod_() 240
_import_() 219
_imul_() 240
_index_() 239
_init_()231
_int_() 238
_invert_() 240
_ior_() 241
_ipow_() 240
_irshift_() 241
_isub_() 239
_iter_() 238
_itruediv_() 240
_ixor_() 241
_le_()241
_1en_() 238
_1shift_() 241
_lt_() 241
_mod_()240
mro 236
_mul_() 239
name 216
_ne_()241
_neg_() 240
_next_()40,207,238,256,268,275,324,
355
_or_()241
_pos_() 240
_pow_()240
_)add_() 239
_rand_()241
_repr_() 239
_rfloordiv_() 240

668

_rlshift_() 241
_rmod _() 240
_rrnul_() 240
_ror_() 241
_round_() 239
_rpow_() 240
_rrshift_() 241
_rshift_() 241
_rsub_() 239
_nruediv_() 240
_rxor_() 241
_setattr_() 237, 244
_setitem_() 236
slots 245
_str_() 239
_sub_() 239
_truediv_() 240
_xor_() 241

243
ABCMeta243
Abon 611,613
about() 618
aboutQt() 618
aboutoActivate()

663
648
aboutToShow() 648
abs()37, 71,179,240
abspath() 260, 262, 281
Accept 353, 625
accept() 386, 425, 442, 448, 455, 456, 458,
463,464,601,604,608,610
Accept-Charset 353
Accepted 608,609,612,619,624
Accept-Encoding 353
acceptHoverEvents() 603
Accept-Language 353
n 624
acceptProposedAction() 463, 464, 604
acceptRichText() 501
AcceptRole 611,612,614
AcceptSave 624
access() 278
AccessiieDescriptionRole 528
AccessiieTextRole 528
accumulate() 158
acos() 72
actionChanged() 461
actionGroup() 651
aboutoHide()

ActionRole 61-1,614
actions() 647, 652, 654
actionTriggered() 520, 655
activated() 517,526,538,664
activateNextSubWintlow() 661
activatePreviousSubWindow() 661
activateWindow() 415,609
ActivationChange 444
ActivationHistoryOrder 660
activationOrder() 661
Active 420
activeAction() 645, 647
ActivePython 20
activeSubWindow() 660
activeWindow() 581
ActiveWindowFocusReason 449
actuaiSize() 577
add() 171
addAction() 645, 646, 652, 654
addActions() 646, 654
addButton() 611,612,615
addDockWidget() 642
addEIIipse() 580
addFile() 576
addltem() 484, 523, 579
addLayout() 470, 473
addLine() 579
addMenu() 645, 647
addPage() 634
addPath() 580
addPerrnanentWidget() 658, 659
addPixmap() 576, 580
addPolygon() 580.
addRect() 580
addRow() 474
addSeparator() 647, 654
addSimpleText() 580
addSpacing() 471
addStretch() 471
addSubWindow() 660
addTab() 481
addText() 580
addToGroup() 597
addTooiar() 641, 653
addTooiarBreak() 642
addWidget() 366, 429, 470-473, 476, 486,
580,654,658,659
Adjust 412, 539
adjustSize() 402
AdjustoContents 525
AdjustoContentsOnFirstShow 525
AdjustToMinimumContentsLength 525

669

AdjustToMinimumContentsLengthWithlcon
525
AeroStyle 635
AlignAbsolute 471
AlignBottom 396,471,565
AlignCenter 369,396,471, 565
AlignHCenter 396,471,479,565
AlignJustifY 471
AlignLeft 396,471,479,565
alignment() 505
AlignRight 396,471,479,565
AlignTop 396,471,565
AlignVCenter 396,471,565
all() 147
AIIDockWidgetAreas 657
AIIEditTriggers 537
AIIFonts 527
AIILayers 584
AIINonFixedFieldsGrow 475
AllowNestedDocks 642, 643
AllowTabbedDocks 642
AIITooiarAreas 654
alpha() 553, 554
alphaF() 553-555
AltModifier 454
AmPmSection 515
anchorCiicked() 512
and 57
animateCiick() 493
AnimatedDocks 642
answerRect() 465
Antialiasing 565
any() 147
AnyFile 624
AnyKeyPressed 537
Apilevel 3\8
append() \10, 133, \34, 144, \96,222,500,
559
appendColumn() 53\, 534
appendRow() 531, 534
ApplicationActivate 444
ApplicationDeactivate 444
ApplicationModa\417, 418,609
ApplicationShortcut 452, 650
Apply 611,613
ApplyRole 611,614
Argv 32, 365, 366
ArithmeticError 255
Arraysize 324
ArrowCursor 458
as 218, 220, 225, 253
as_string() 351

AscendingOrder 530, 533, 536, 542, 544, 549,


581
ASCII\15, 118,\19
ascii() 91,94
asctime() 176
asin() 72
assert 255, 258
AssertionError 255, 258
Assistant 361
astimezone() 188
atan() 72
atBiockEnd() 51
atiockStart() 51
atEnd() 509
atStart() 509
AttributeError 217,229,237,245,255
AutoAII 503
AutoBulletList 503
AutoCompatConnection 430
autoCompletion() 525
AutoConnection 429, 430, 435
AutoNone 503
AutoText 490, 615, 635
availaieGeometry() 405, 406
availaieRedoSteps() 506
availaieSizes() 576
availaieUndoSteps() 506

back() 634
BackButton 635
Background 420
BackgroundLayer 583
BackgroundPixmap 636
BackgroundRole 527
backspace() 496
BacktabFocusReason 449
backward() 511
backwardA vailaie() 512
backwardHistoryCount() 511
BannerPixmap 636
BaseException 255
basename() 282
baseSize() 402
Batched 540
begin() 562
beginEditBiock() 51
Beve\Join 556
Bin 518
bin()71,239
Black 396, 504, 507, 552, 554, 560

670
BlankCursor 458
509
lockCount() 507
lock()

lockCountChanged()

507
BlockingQueuedConnection 430
lockNumber() 509
lockSignals() 430
BlockUnderCursor 51
Blue 552, 553
lurRadius() 598, 599
lurRadiusChanged() 599
Bold 504, 507, 560
23,264
)38,44,55,238

bottom() 4 12
BottomDockWidgetArea 642, 643, 657
bottomLeft() 413
BottomLeftCorner 643
bottomRight() 413
BottomRightCorner 643
BottomTooiarArea 641, 654
BottomToTop 472,519
boundedTo() 409
boundingRect() 559, 561, 565, 566, 588

BoundingRectShape 595
480
break 62, 66---68
bspTreeDepth() 579
BspTreelndex 579
Buffer 270
Builtins 34
BusyCursor 458
button() 456, 602, 612, 615, 635
buttonCiicked() 6!5
buttonDownPos() 602
buttonDownScenePos() 602
buttonDownScreenPos() 602
buttonRole() 6\2, 615
button~)456,458,602,603,605,6\2,6\5

buttonText() 636, 637


Byte Order Mark 23, 264
Bytearray 38, 45, 46, 77, 105, 108, 109
Bytes 38, 45, 77, 105, 106,263,327,332
Bytes!O 276

CacheBackground 585
Cache-Control 353
CacheNone 585
Calendar 173, \89, 192, 194
Cance\610,613,633

Canceiutton

635

CanceiuttonOnLeft

636
canceled() 633
canPaste() 50\
capitalize() 98
cascadeSub Windows() 661
Caselnsensitive 506, 525, 549, 550
CaseSensitive 525, 549, 550
ceil() 73
center() 89, 413
centerOn() 587 .
centra\Widget() 640
cgi348
chain() 158
changed()584,652
changeEvent() 445
changeOverrideCursor() 459
characterCount() 507
chardet 357
chdir() 262, 290
Checked 494, .528, 535
checkedAction() 652
checkOverflow() 518
checkState() 494, 535
CheckStateRole 528
child() 529, 534
ChildAdded 443
childltems() 59\
ChildPolished 443
ChildRemoved 443
chmod() 278
choice() 74, 75, 148
chr() 98
Class 228, 229
ClassicStyle 635, 636
cleanText() 513
cleanupPage() 634, 636, 639
clear() \66, 171, 289, 463, 465, 482, 491, 496,
501,505,513,524,53\,548,559.573,580.
612,645,647,654
ClearAndSelect 548
clearEditText() 525
clearFocus() 449, 582, 590
clearHistory() 511
clearMessage() 396, 659
clearSelection() 510,537,548,583
clearSpans() 541
clearUndoRedoStacks() 506
click() 434, 493
clicked() 367,384,426,427,431,433,479,
492,493,517,538,612
clickedButton() 615

ClickFocus 450
Clipboard 443, 465
clone() 535
close() 265, 272, 273, 288, 319, 349, 355, 358,
424,425,443,448,610,613,650
closeActiveSub Window() 661
closeAI\SubWindows() 661
closeAI\Windows() 424
Closed 270, 273
ClosedHandCursor 458
closeEvent() 386, 425, 442, 445, 448.
Cmath 72
Cmyk 555
Code 355
collapse() 544
col\apseA 11() 544
collapsed() 544
collidesWithltem() 592
collidingltems() 581, 591
color() 598, 599
colorO 552, 572, 573
colorl 552, 572
colorChanged() 599, 600
colorNames() 552
column() 529, 533
columnCount() 473,531, 533
columnlntersectsSelection() 547
Columns 548
columnSpan() 541
column Width() 541, 543
cominations() 154
cominations _ with _replacement() 155
comine() 186
commit() 321, 327, 328, 339
CommitButton 635
compile() 114, 123, 124, 127, 128
complete_ statement() 338
completeChanged() 638
complex 38, 69
complex() 239
compress() 157
Confidence 357
connect() 319, 328, 334, 367, 369, 383, 384,
426,428,429,431,435,438
contains() 413, 414
ContainsltemBoundingRect 582, 583, 585
ContainsltemShape 581, 583, 585
Content-Length 350, 353
contentsChange() 507
contentsChanged() 508
Content-Type 350,352-354
Context 664

671
ContextMenu 444, 663
contextMenuEvent() 497, 501, 644, 648, 649
ContiguousSelection 537
Continue 67
ControiModifier 454
convertFromlmage() 571
convertTo() 555
convertToFormat() 575
Cookie 353
135,161,166,170,172,279,454,497,
501,571,575,.650
2() 279
Action 460, 461
vailaie() 502
copyfile() 278
comer() 643
cornerWidget()488
cos() 72
count() 65, 100, 147, 153,476,483,485,487,
524,545,559
create_aggregate() 331
create_ collation() 328
create_function() 330, 331
createltemGroup() 580, 597
createPopupMenu() 641
createStandardContextMenu() 497, 501
CreationOrder 660
Critical613, 617,618,664
CrossCursor 458
CrossPattem 421, 557
cssclasses() 191
ctime() 176, 182, 188
Current 548
currentChanged() 476, 477, 483, 485, 537,
548,625
currentCharFormat() 505
currentCharFormatChanged() 502
currentColumnChanged() 549
currentFont() 504, 527
currentFontChanged() 527
currentld() 634
currentldChanged() 63 7
currentlndex() 476, 483, 485, 524, 529,
536,548
currentlndexChanged() 526
currentMessage() 659
currentPage() 634
currentPageChanged() 517
currentRowChanged() 548
currentSection() 515
currentSectionlndexO 515
currentSubWindow() 660

672
currentext()

524
currentWidget() 476, 483, 485
cursor() 319, 459
cursorBackward() 497
cursorForPosition() 508
cursorForward() 496
cursorPosition() 496
cursorPositionChanged() 497, 502, 507
cursorWordBackward() 497
cursorWordForward() 497
CustomButton1 635,636,637
CustomButton2 635, 637
CustomButton3 635, 637
customButtonCiicked() 637
CustomDashLine 555
customEvent() 467
CustomizeWindowHint 400
cut() 497, 50 1, 650
cyan() 552, 554
cyanF() 554
cycle() 154

D
DarkBiue 552
DarkCyan 552
darker() 553
DarkGray 552
DarkGreen 552
DarkMagenta 552
DarkRed 552
DarkYellow 552
DashDotDotLine 542, 555
DashDotLine 542, 555
DashLine 542, 555
data()463,529,530,532,535,651
DatabaseError 337
dati:tChanged() 465
DataError 337
Date 178, 180-182, 186, 187,336,514-517
dateChanged() 515
Datetime 173, 178, 180, 183, 184, 186-188,
336,514,515
dateTimeChanged() 515
Day 181, 186
Day_abbr 194
Day_ name 194
Days 178, 179
DaySection 515
DB-AP1318
Dbm 288,293

Dec518
Decimal 50, 70
DecorationRole 527
deepcopy() 135, 161, 166
Def197, 199,229
defaultAction() 647, 656
defaultSectionSize() 545
degrees() 73
De\47, 111, 146, 163,289
del_() 496
delattr() 230
DelayedPopup 656
deleteChar() 51
deletePreviousChar() 51
deleter() 246
delta() 458, 603
DemiBold 504, 507, 560
Dense 1Pattern 421, 557
Dense2Pattern 421, 557
Dense3Pattern 421, 557
Dense4 Pattern 4 21 , 55 7
Dense5 Pattern 4 21 , 55 7
Dense6Pattern 421, 557
Dense7Pattern 421, 557
depth() 571, 574
DescendingOrder 530, 533, 536, 542, 544,
549,581
Description 323
Deselect 496, 548
Designer 361,371,373
Desktop 400, 405
destroyltemGroup() 580, 597
DestructiveRo1e 6"11, 614
Detai\624
detect() 357, 358
Detect_types 334
Dialog 400
dict() 39, 159, 161,351
Dict_items 164
Dict_keys 62, 164
Dict_values 164
difference() 168, 172
difference_ update() 168
digest() 113
dir() 35,219
DirectConnection 429
Directory 624, 625
directoryEntered() 626
dirname() 262, 283
Disaied 420
DisaiedBackButtonOnLastPage 636
Discard 171,611,613

673

disconnect() 430, 431, 435


display() 518
DisplayRole 527, 532, 549, 550
displayText() 496
divmod() 72
dockLocationChanged() 65 8
dockOptions() 643
dockWidgetArea() 642
DockWidgetCiosa\e 657
DockWidgetFioata\e 657
DockWidgetMova\e 657
DockWidgetYerticaiTitleBar 657
document() 505, 51 , 596
documentMargin() 507
documentTitle() 500
done() 358, 608, 61
DontConfirmOverwrite 624
DontMaximizeSub WindowOnActivation 661
DontUseNativeDialog 629, 631
DontWrapRows 475
DOTLL 114, 116
DotLine 542, 555
Dou\eCiick 664
dou\eC\icked() 537, 539
dou\eC\icklnterval() 455
Dou\elnput 619,620,621
dou\eYalue() 620
dou\e YalueChanged() 62 1
dou\e YalueSelected() 62 1
Down 508
DownArrow 656
DragDrop 538
DragEnter 443
dragEnterEvent() 463, 464, 604
DragLeave 443
dragLeaveEvent() 463, 604
dragMode() 585
DragMove 443
dragMoveEvent() 463, 604
DragOnly 538
draw() 597, 598
drawArc() 564
drawBackground() 579
drawChord() 564
drawE\Iipse() 564
Drawer 400
drawForeground() 579
drawlmage() 566, 567, 573
drawLine() 563
drawLines() 563
drawPicture() 569
drawPie() 564
22

. 13~9

drawPixmap() 566, 570, 572


drawPoint(} 563
drawPoints() 563
drawPolygon() 564
drawPolyline() 563
drawRect() 563
drawRoundedRect(} 564
drawText() 565
Drop 443
dropAction() 464, 604
dropEvent() 463, 464, 604
DropOnly 538
dropwhi\e() 156
dst() 184, 188
dump() 286, 287
dumps() 1 12, 287
dup() 272
dx() 558
dy() 558

East 482, 643, 661


Eclipse 14, 365
editingFinished(} 497, 513
EditKeyPressed 537
EditRole 527, 532
editTextChanged() 526
ElideLeft 482, 537
ElideMiddle 482, 538
ElideNone 482, 538
ElideRight 482, 537
ElifO

Ellipsis 39
Ellipsis 39
Else 62, 66, 25 1
emit() 382, 383, 388, 433---435
Empty 389, 390
ena\edChanged() 598
Encoding 270, 357
End 508
end() 126,497,562
endEditB\ock() 51
EndOtlock 508
EndOfLine 508
EndOfWord 508
Endpos 125
endswith() 100
ensureCursorYisi\e() 501
EnsureYisi\e 538
ensureYisi\e() 487, 587, 592
ensureWidgetYisi\e() 487

674

Enter 443
entered() 539
enterEvent() 457
enumerate() 65, 140
Env 25
EOFError 255, 284
Error 337
escape() 131, 34 7, 348
eval() 32
event() 444, 452, 455, 467, 651
eventFilter() 465, 466
exc_info() 249, 253
except248--251,256
Exception 255, 257, 337
_()367,379,386,388,460,608,609,

614,619,624,644,648,649
execute() 320--322, 331
executemany() 322
executescript() 319, 322
ExistingFile 624
ExistingFiles 624
exists() 279
exit() 365, 367, 379, 386, 424
() 73
expand() 126, 544
expandA\1() 544
expanded() 544
expandedTo() 409 .
Expanding 475, 477
ExpandingFieldsGrow 475
expandtabs() 88
expandToDepth() 544
extend() 11 , 145
ExtendedSelection 537
ExtendedWatermarkPixmap 636
extension() 608

F
F 278
fabs() 73
factorial() 73
Fa1se 38,55
families() 561
family() 560
FastTransformation 572, 575, 595
fdopen() 272
features() 657
feed() 358
fetcha\1() 325
fetchmany() 324
fetchone() 324

field() 635, 638


FieldsStayAtSizeHint 475
FileName 625
fileno() 268, 283
fileSelected() 626
filesSelected() 626
FileType 625
fill() 571' 574
Filled 518
fii\Rect() 564
filter() 143, 144
filterfalse() 156
filterSelected() 626
finalize() 331
Finally 251
find() 99,501,506
findall() 127
FindBackward 501, 506
findBiock() 507
findBiockByNumber() 507
FindBuffer 465
FindCaseSensitively 501, 506
findData() 526
findltems() 532
finditer() 128
findText() 526
FindWholeWords 501,506
finish() 396
FinishButton 635
finished() 382, 384
Firebug 354
firstBiock() 507
firstweekday() 192
fitlnView() 587
Fixed 477, 539, 545
FixedColumnWidth 503
FixedPixeiWidth 503
tlags() 529, 535, 589
Flat 518
FlatCap 556
tloat() 38, 44, 69, 70, 238
tloor() 73, 220
tlush() 268, 275, 286
fmod() 73
Focusln 443, 450
focuslnEvent() 450, 60 1
focusltem() 582
focusNextChild() 449
focusNextPrevChi1d() 449
FocusOut 443, 450
focusOutEvent() 450, 601
focusPolicy() 450

675

focusPreviousChild() 449
focusProxy() 449, 601
focusWidget() 449,450
font() 595, 596, 651
fontFamily() 504
fontltalic() 504
fontPointSize() 504
FontRole 527
fontUnderline() 504
fontWeight() 504
for30,40,61--63,65,83, 139--141,163,
167, 168, 172, 196,207,268,275,324
ForblddenCursor 458
ForceTabbedDocks 642
Foreground 420
ForegroundLayer 584
ForegroundRole 527
format() 84, 90, 91,574
Format ARG32 574
Format_ARG32_premultiplied 573, 574
format_exception() 249
format_ exception _ only() 249
Format lndexed8 574
Format lnvalid 573
Format Mono 573
Format MonoLSB 574
Format RGB32 574
formatmonth() 190, 191
formats() 463
formatyear() 191
formatyearpage() 192
forward() 511
forwardA vailaie() 512
forwardH istoryCount() 511
Fractions 70
Fragment 341, 342
frameGeometry() 403, 404
FramelessWindowint 400
frameSize() 403, 405
Free 539
Friday 517
FRIDAY 190
m219,220,224--227,258

from_itera\e() 158
fromCmyk() 554
fromCmykF() 554
fromData() 574
fromhex() 106, 109
fromHsv() 554
fromHsvF() 554
from1mage() 571, 573
fromkeys() 160

fromordinal() 181, 186


fromRgb() 553
fromRgba() 553
fromRgbF() 553
fromtimestamp() 181, 185
frozenset 39, 171, 172
frozenset() 171
fu1\() 389, 390
function 39, 199
functools 144, 438

G
geometry() 403, 404, 664
GET
get() 162, 165, 289, 348, 349, 352, 353, 355,
356,389,391
get_all() 352
get_content_maintype() 352
get_content_subtype() 352
get_content_type() 352
get_nowait() 389
getatime() 21
getattr() 211: 229
getbuffer() 276
getCmyk() 554
getCmykF() 554
getCo1or() 629
getCoords() 413
getctime() 280
getcwd() 289
getDouie() 622
getExistingDirectory() 626
getFont() 630
getheader() 350
getheaders() 350
getHsv() 554
getHsvF() 555
getlnt() 621
getlnteger() 621
getltem() 623
getloca1e() 97
getmtime() 280
getOpenFileName() 627
getOpenFileNameAndFilter() 627
getOpenFileNames() 628
getOpenFileNamesAndFilter() 628
getparam() 352
getRect() 4 13
getrefcount() 42
getresponse() 349
getRgb() 553

676
getRgba() 630
getRgbF() 553
getSaveFileName() 628
getSaveFileNameAndFilter() 628
getsize() 279
getter() 246
getText() 621
geturl() 342, 355
getvalue() 273
glob() 292
global() 2 1 1
globaiPos() 456, 458, 648, 649
globals() 212
globaiX() 456, 458, 648
globaiY() 456, 458, 648
gmtime() 173, 174, 194
gotFocus() 450
grabKeyboard() 450, 455, 590, 601
grabMouse() 456, 457, 590, 602
grabShoncut() 452
grabWidget() 572
grabWindow() 572
graphicsEffect() 597
green() 553
greenF() 553
group() 125, 597
groupdict() 125
groupindex 124
groups() 124, 126
GroupSwitchModifier 454

hasAcceptaelnput() 498, 499


hasattr() 217, 230
hasChildren() 533, 534
hasComplexSelection() 51
hasFocus() 449, 582, 590
hasFormat() 463
hashlib 112
hasHtml() 462
haslmoge() 462
hasSelectedText() 491, 496
hasSelection() 51 , 54 7
hasText() 462
hasTracking() 520
hasUrls() 462
hasVisitedPage() 634
HaveCustomButton 1 635, 636
HaveCustomButton2 635, 637
HaveCustomButton3 635, 637
HaveFinishButtonOnEarlyPages 636

HaveHelpButton 635, 636


HaveNextButtonOnLastPage 636
HEAD 348, 349, 352
header() 543, 545
headerData() 532
height() 402,405,408,412,561,571,574,579
heightForWidth() 478
Help 611,613
help() 33, 34, 35, 37
HelpButton 635
HelpButtonOnRight 636
helpRequested() 612, 637
HelpRole 61 1, 614
HeuristicMaskShape 595
518
hex() 71,239
hexdigest() 1 13
hiddenSectionCount() 546
hide()386,399,443,590,609,610,663
hideColumn() 542, 543
hideEvent() 445
HideNameFilterDetails 625
hidePopup() 525
hideRow() 541
hideSection() 546
hideTearOftenu() 647
HideToParent 443
HighestPriority 382
highlighted() 512, 526
HighPriority 382, fJ5 1
historyChanged() 51 2
historyTitle() 51 1
historyUrl() 51 1
HLine 480
home() 4?7, 511
Horizontal 458, 486, 519, 520, 522, 532, 545,
603,609--611,642,644
horizontaiHeader() 541, 545
horizontaiHeaderltem() 532
horizontaiScroiiBar() 487
Host 353
hostname 341
hotSpot() 461
hour 183, 185, 186
hours 178
HourSection 515
hover() 652
hovered() 645, 648, 652, 653
hoverEnterEvent() 602
hoverLeaveEvent() 602
hoverMoveEvent() 602
Hsl555

Hsv 555
hsvHue() 554
hsvHueF() 555
hsvSaturation() 554
hsvSaturationF() 555
html 348, 462
HTMLCalendar 189, 191
http.client 340, 348, 355
http.client.HTTPMessage 351
HTTPConnection 348
- 353

\eamCursor

458
icon() 647, 649, 663
lconMode 539
iconSize() 642, 655
IDLE 14, 20, 23, 28, 364
ldlePriority 382
ieHTTPHeaders 3~4
if... else 58, 59, 61
ignore() 386, 425, 442, 448, 455, 456, 458,
464,601,611,613
lgnoreAction 460
lgnoreAspectRatio 409,571,575
IGNORECASE 114
lgnored 477
lgnoreSubTitles 636
imageData() 462
lmp 223
lmport 24, 31,216,218-221,225-227
lmportError 255
in 52, 56, 76, 84, 147, 152, 162, \64, 169, 241,
289
Inactive 420
lndentationError 255
lndependentPages 634; 636, 639
index() 65, 99, 147, 153,247, 529,530, 532,
536
lndexError 81, 125, 137, 146,255
indexesMoved() 540
indexFromltem() 532
indexOf() 477,483,485,487
indexWidget() 536
info() 355
information() 613, 616, 664
lnheritPriority 382
initializePage() 634, 636, 638
input() 24, 31-33, 35, 46, 255, 284
inset() 11 , 111, 145, 222, 496, 559
insertAction() 647, 654

677
insertActions() 647, 654
lnsertAfterCurrent 524
lnsertAiphabetically 524
lnsertAtottom 524
lnsertAtCurrent 524
lnsetAtTop 524
InsertBeforeCurrent 524
insertBiock() 511
insertColumn() 531, 534
insertColumns() 531, 534
insertFragment() 511
insertFrame() 511
insertHtml() 500, 51
insertlmage() 51\
insertltem() 484, 523
insertltems() 524
insertLayout() 470
insertList() 511
insertMenu() 645, 647
insertPermanentWidget() 658, 659
insertPiainText() 500
insertRow() 474, 531, 534
insertRows() 530, 531, 534
insertSeparator() 524, 647, 654
insertSpacing() 471
insertStretch() 4 71
insertTab() 482
insertTaie() 51\
insertText() 51
insertToo\ar() 641, 653
insertToo\arBreakO 642
insertWidget() 470,471,476,486,654,658,
659
instaiiEventFilter() 466
instaiiSceneEventFilter() 605
lnstantPopup 656
int()38, 44, 69, 70, 238
IntegrityError 337, 339
lnteractive 545
lnterfaceError 337
lnternaiError 337
lnternaiMove 538
intersect() 4 14
intersected() 414
intersection() 169, 172
intersection _update() 169
intersects() 414
lntersectsltemBoundingRect 582, 583, 585
lntersectsltemShape 58\, 583, 585
interval() 440, 441
lntlnput 619---621
intValue() 518, 620

678
intValueChanged() 620
intValueSelected() 621
lnvalid 555
invalidate() 583
invalidateScene() 588
lnvalidRole 611,612,614
invenPixels() 576
InvenRgb 576
JnvenRgba 576
invisiieRootltem() 532
io 269, 273, 276
IOError 255, 259, 263, 278, 279
is 41, 56, \34, \35
isabs() 282
isAccepted() 442
isActive() 441, 562, 583
isActive Window() 415
isalnum() 103
isalpha() 103
isAmblguous(} 452
isatty() 284
isAutoRepeat() 454
isBackwardA vailaie() 511
isCheckaie() 479, 535, 650
isChecked() 479, 493--495, 650
isColumnHidden() 542, 543
isColumnSelected() 547
isCommitPage() 638
isComplete() 638
isdecimal() 102
isdigit() 102
isdir(} 291
isdisjoint() 170, 172
isDockNestingEnaied() 643
isDown()493
isEmpty() 408,4\3,505,559,647
isEnaied() 432, 493, 590, 598, 651, 653
isExpanded() 544
isfile(} 291
isFinaiPage() 638
isFinished() 382
isFiat(} 479
isFioataie() 655
isFioating() 655, 657
isForwardA vailaie() 511
isFuiiScreen() 415
isHeaderidden() 543
isHidden() 399
islndexHidden() 542, 544
isinstance() 44
islnteractive() 585
isltemEnaied() 485

isleap() 193
islink() 292
islower() 103
isMaximized() 415
isMinimized() 415
isModal() 417, 609
isModified() 505
isMovaie() 546, 654
isNull() 379,407,408, 4\3, 506, 509, 557,
570,574,576
isnumeric() 102
isocalendar() 183, 188
isoforinat() 182, 184, 188
isolation level 328
isoweekdayO 182, 188
ISOWeekNumbers 517
isQBitmap() 571
isReadOnly() 496, 503
isRedoAvailaie() 497,506
isRowHidden() 540, 542, 543
isRowSelected() 547
isRunning() 382, 386
isSectionHidden() 546
isSelected() 547, 590
isSeparator() 649
isShaded() 662
isSingleShot() 441
isSizeGripEnaled() 609
isspace() 103
issubset() 170, 172
issuperset() 170, 172
isSystemTray vailaie() 663
isTabEnaied() 483
isTearOftEnaied() 647
isTearOffenuVisile() 647
istitle() 103
isTristate() 495, 535
isUndoAvailaie() 497, 505
isUndoRedoEnaled() 501, 506
isupper() 103
isValid() 408,413, 529, 552
isValidColor() 552
isVisi\e() 399,590,651,653,664
italic() 560
item() 532
itemAt() 581, 586
itemChange() 605,606
itemChanged() 533.
ItemCursorChange 606
ItemCursorHasChanged 606
itemData 524
ItemDoesntPropagateOpacityToChildren 589


ltemEnaiedChange

605

ltemEnaiedHasChanged

605

ltemFiagsChange 606
ltemFiagsHaveChanged 606
itemFromlndex() 532
ltemlgnoresParentOpacity 589
ltemlgnoresTransformations 589
ltemlsDragEnaied 529
ltemlsDropEnaied 529
ltemlsEditaie 529
ltemlsEnaied 529
ltemlsFocusaie 582, 589, 590, 600
ltemlsMovaie 589
ltemlsPanel 589
ltemlsSelectaie 529, 582, 585, 589, 590
ltemlsTristate 529
ltemlsUserCheckaie 529
ltemLayer 583
ltemMatrixChange 605
ltemOpacityChange 606
ltemOpacityHasChanged 606
ltemPositionChange 605
ltemPositionHasChanged 605
items() 164, 288, 351, 581, 586
itemsBoundingRect() 579
ltemScenePositionHasChanged 606
ltemSelectedChange 606
ltemSelectedHasChanged 606
ltemSendsGeometryChanges 605, 606
ltemSendsScenePositionChanges 606
ltemStacksBehindParent 589
itemText() 485, 524
ltemTooiTipChange 606
ltemTooiipHasChanged 606
ltemTransformChange 606
ltemTransformHasChanged 606
ltemVisiieChange 606
ltemVisiieHasChanged 606
ltemZValueChange 606
ltemZValueHasChanged 606
iter() 40
itertools 157

J
join() 96, 151, 283, 389
joinPreviousEditiock()

51

KeepAnchor 509
KeepAspectRatio 409, 571, 575

679

KeepAspectRatioByExpanding 409, 571, 575


key() 452, 454
Keyboardlnterrupt 66, 256
.
keyboardModifiers() 464
KeyErrorl62, 165,171,255,289
KeypadModifier 454
KeyPress 443, 444, 465
keyPressEvent() 442, 454, 601
KeyRelease 443
keyReleaseEvent() 454, 601
keys() 62, 163, 164,288,326,352
killTimer() 439, 440, 441

L
Lambda205
lastBiock() 507
Lastgroup 125
La5tindex 125
Last-Modified 353
lastPos() 602, 603
Lastrowid 323
lastScenePos() 602, 603
lastScreenPos() 602, 603
LC ALL 97
LC_COLLATE 97
LC 97
LC_MONETARY 97
LC NUMERIC 97
LC TIME 97
leapdays() 193
Leave 443
leaveEvent() 457
left() 412, 508
LeftArrow 656
LeftButton 456, 458
LeftDockWidgetArea 642, 643, 657
LeftToo\arArea 641, 654
LeftToRight 471,540
len() 64, 83, 94, 136, 153, 163, 168, 238, 289,
477,483,485,487
LifoQueue 388
Light 504, 507, 560
lighter() 553
LightGray 552
line() 593
lineCount() 507
LineUnderCursor 51
Linguist 361
LinkAction 460, 461
linkActivated() 492, 596
linkovered() 492, 596

680
LinksAccessieByKeyboard

491, 502
491, 502
list() 38, 46, 96, 132, 134, 135, 148,624
listdir() 290-292
ListMode 539
ListView 536
ljust() 89
load() 286, 287, 569, 570, 574
loadFromData() 570, 574
loads() 112, 288
loadUi() 373
loadUiType() 374
locale 97
LOCALE 114
localeconv(} 98
LocaleHTMLCalendar 189, 191
LocaleTextCalendar 189, 190
locals() 212
localtime() 174, 515
Location 353, 354
lock() 392
log() 73
logicallndex() 546
LogoPixmap 636
LongDayNames 5 17
Lookln 625
lostFocus() 450
lower() 98
LowestPriority 382
LowPriority 382, 651
lsee 272
lstrip() 94
LinksAccessieByMouse

MacStyle 635, 636


magenta() 554
magentaF() 554
maketrans() 1 1
manhattanLength() 407
ManuaiWrap 503
map() 141, 142, 143
mapFrom() 457
mapFromGiobal() 457
mapFromParent(} 457
mapFromScene() 586
mapTo() 457
mapToGiobal() 457
mapToParent() 457
mapToScene() 586
mask(} 423, 571
MaskShape 595

match() 123, 124


MatchCaseSensitive 526
MatchContains 526
MatchEndsWith 526
matches() 454
MatchExactly 526
MatchFixedString 526
MatchRecursive 526
MatchRegExp 526
MatchStartsWith 526
MatchWildcard 526
MatchWrap 526
Math 72, 217, 218, 220
matrix() 587, 591
max() 71, 147
Maximum 477
maximumBiockCount() 507
maximumHeight() 402
maximumSize() 402
maximumWidth() 402
MaxUser 444
MAXYEAR 180, 181, 184, 186
md5() 112, 113
mdiArea() 662
DI-n 640, 659
memoryview() 276
menu(} 494, 651, 656
menuAction() 647
menuBar() 641, 645
MenuBarFocusReason 449
MenuButtonPopup 656
menuWidget() 641
mergeBiockCharFormat() 511
mergeBiockFormat() 511
mergeCharFormat() 511
messageChanged() 659
messageCiicked(} 664
MetaModifier 454
microsecond 183, 185, 186
microseconds 178, 179
MidButton 456, 458
MiddleButton 456
MiddleCiick 664
milliseconds 178
mimeData() 461, 464, 465, 604
min()72, 147
Minimum 477
MinimumExpanding 475,477
minimumHeight(} 402
minimumSectionSize() 545
minimumSize() 402
minimumSizeHint() 402

minimum Width() 402


minute 183, 185, 186
minutes 178
MinuteSection 515
MINYEAR 180, 181, 184, 186
mirrored() 576
MiterJoin 556
mkdir() 290
mktime() 174
mode 270
model() 529, 536, 539, 541, 543
ModernStyle 635, 636
modificationChanged() 508
modifiers() 454, 456, 458, 602, 603, 605
Module 39,219
Monday 190, 517
MonospacedFonts 527
Month 181, 186, 192
Month abbr 194
Month name 194
monthcalendar() 193
monthrange() 193
MonthSection 515
monthShown() 516
MouseButtonDICiick 443
MouseButtonPress 443, 444, 465, 466
MouseButtonRelease 443
mouseButtons() 464
mouseDouieCiickEvent() 455, 601
MouseFocusReason 449
mouseGrabberltem() 583, 602
MouseMove 443
mouseMoveEvent() 456, 460, 601
mousePressEvent() 455, 460, 601, 605
mouseReleaseEvent() 455, 601
move()279,403,443,468
MoveAction 460, 461
MoveAnchor 509
moveBottom() 412
moveBottomLeft() 412
moveBottomRight() 412
moveBy() 589
moveCenter() 4 12
moveCursor() 508, 509
moveEvent() 446
movePosition() 509
moveRight() 412
moveSectlon() 546
moveTo() 411
moveTop() 411
moveTopLeft() 412
moveTopRight() 412

681

MSecSection 515
Msg 351,355
msleep() 384
MS WindowsFixedSizeDialogH int 400
MULTILINE 114, 116
Multiprocessing 395
MultiSelection 537

N
Name 270, 271, 552
NameError 256
Netbtjans 14
Netloc 341
next() 40, 65, 634
NextBiock 509
NextButton 635
NextCell 509
NextCharacter 509
nextld() 634, 638
NextRow 509
NextWord 509
No 610,613
NoArrow 656
NoBackButtonOnLastPage 636
NoB~ckButtonOnStartPage 636
NoBrush 421,557,563
NoButton 456, 61 , 613
NoButtons 512, 620, 629, 631
NoCanceiButton 635, 636
NoDefaultutton 636
NoDockWidgetArea 642
NoDockWidgetFeatures 657
NoDrag 585
NoDragDrop 538
NoEcho 495, 619
NoEditriggers 537
NoFocus 450
NoFrame 480
NoHorizontaiHeader 517
Nolcon 613, 664
Nolndex 579
Nolnsert 524
NoltemFiags 529
NoModifier 454
NoMove 508
None 38,56
NoneType 38
NonModal 417, 609
NonRecursive 392
NonScalaieFonts 527
NoPen 542, 555, 563

682
Nonnal420,495,504,507,560,619
nonnalized() 413
NonnaiPriority 382, 651
nonnpath() 283
NoRole 611,612,614
North 482, 643, 661
NoSection 515
NoSelection 517, 537
Not 57
Notepad++ 14, 24
NoTextlnteraction 491, 502
NoTicks 521
NoToAII610, 613
NoTooiarArea 641
NotSupportedEor 338
NoUpdate 548 .
No VerticaiHeader 517
now() 185
NoWrap 503

APPEND271
BINARY 271
CREAT271
O_RDONLY 271
RDWR271

271

O_TRUNC271
O_WRONLY 271
Object 234
oct() 71,239
offset() 595, 598
offsetChanged() 599
OffsetFromUTC 515
Ok 610,613
o\dPos() 446
o\dSize() 446
o\dState() 445
opacity() 589, 600
opacityChanged() 600
opacityMask() 600
opacityMaskChanged() 600
open()254,259,261--263,265,271,272,
288,609,610,613,650
OpenHandCursor 458
Operationa\Eor 327, 337
or 58
ord() 99
orientation() 458, 603
os 262,271,278--281,289
os.path 260, 262, 279, 281, 282, 291

OSEor 271
OtherFocusReason 449
Outline 518
overflow() 518
OverflowError 174
overline() 561
oveideCursor() 459
overwriteMode() 503

pl() 558
2() 558
page() 634
pageAdded() 637
pagelds() 634
pageRemoved() 637
Paint 443
paint() 588
paintEvent() 447,551,562
palette() 420, 421
Pane\480
Params 341
parent() 529, 533, 534
parentltem() 591
parentWidget() 399
PARSE COLNAMES 334
PARSE DECLTYPES334
parse_qs() 343, 344
parse_qsl() 344
ParseResult 340, 341
partial() 438
PartiallyChecked 494, 528, 535
partition() 96
Pass 197., 230
Password 342, 495, 496, 619
PasswordEchoOnEdit 495, 619
paste() 497, 501
Path 341
-8 14
permutations() 155
Phonon 377
Pi 72,217,220
Pick\e 112, 286-288, 293
pixe\() 575
pixe\Size() 560
pixmap() 396,461,577,595
Plain 480
PlainText 490, 615, 635
PlusMinus 512
point() 559
PointingHandCursor 458

pointSize() 560
pointSizeF() 560
Polish 443
PolishRequest 443
polygon() 594
() 111, 146, 165, 171,289
popitem() 165, 289
popup() 400, 648
PopupFocusReason 449
popupMode() 656
Port 341
pos() 125,404,446,455,457--459,464,589,
602---604,648
posF() 456
position() 509
PositionAtottom 538
PositionAtCenter 538
PositionAtop 538
positionlnBiock() 509
possiieActions() 464, 604
POST 348, 349, 353, 355, 356
postEvent() 466
pow() 71,73
Pragma 353
prca\() 193
Preferred 4 77
prepareGeometryChange() 589
PrepareProtocol 333
prepend() 559
pressed() 493, 538
PreviousBiock 508
PreviousCe\1 509
PreviousCharacter 508
PreviousRow 509
PreviousWord 508
print() 28-31,239,284
print_() 502, 506
print_exception() 249
print_tb() 249
priority() 382, 651
PriorityQueue 389
prmonth() 190, 193
processEvents() 380, 381, 632
product() 155
ProgrammingError 338
property() 245
Proportionalfonts 527
proposedAction() 464, 604
pryear() 191
put() 389
put_nowait() 389
PyDev 14, 365

683
Pydoc 33
PyQt_PyObject 434
PYQT_VERSION_STR 362
PyQt4 377
pyqtSignal() 435
pyqtSiot() 429, 437
PyScripter 14, 24
Python Shell 23
python.exe 17, 18
PYTHONP 222
pythonw.exe 17
PythonWin 14
pyuic4.bat 375

Q
QAbstractButton 492, 493, 494
QAbstractGraphicsShapeltem 593
QAbstractltemView 529, 536------540, 543, 545,
547
QAbstractListModel 530
QAbstractProxyModel 549
QAbstractScrollArea 487
QAbstractSiider 520---522
QAbstractSpinBox 512-514
QAction 453, 644, 645, 647---649, 651---657
QActionGroup 651---653
QApp 365, 367
QApplication 365, 379, 419, 420, 424, 450,
455,459,460,465,560
QAxContainer 377
QBitmap 557, 569, 572, 573
QBoxLayout 471
QBrush 421, 556, 557
QButtonGroup 494
QByteArray 378, 419, 569
QCalendarWidget 516, 517
QChar 378
QCheckBox 494
QCiipboard 465
QCioseEvent 425, 448
QColor 396, 420, 504, 551, 555, 556, 574, 575
QColorDialog 629, 630.
QComboBox 523-527, 529, 536, 620
QCompleter 495, 525
QConica\Gradient 557
QContextMenuEvent 648
QCoreApplication 380, 466
QCursor 458, 459
QDate 379,514-517
QDateEdit 514, 515
QDateTime 379,514,515

684
QDateTimeEdit 514, 515
QDesktopWidget 406
QDial521
QDialog 368, 370, 398, 418, 419, 607---Q09
QDialogButtonBox 610-612
QDockWidget 644, 656, 657
QDouieSpinBox 512, 513
QDouieVa1idator 499
QDrag 460, 461, 462
QDragEnterEvent 463, 464
QDragLeaveEvent 463, 464
QDragMoveEvent 463, 464
QDropEvent 464
QErrorMessage 631
QEvent 442, 457, 464, 466, 602---Q04
QFileDia1og 607, 623---Q26
QFocusEvent 450, 601
QFont 504, 506,560
QFontComboBox 526, 527
QFontDatabase 561
QFontDialog 630, 631
QFontMetrics 561
QFontMetricsF 561
QFormLayout 473-475
QFrame 368, 398, 479, 480
QGraphicsBiurEffect 599
QGraphicsColorizeEffect 599, 600
QGraphicsDropShadowEffect 598, 599
QGraphicsEffect 597, 598
QGraphicsEIIipseltem 578, 580, 592, 594
QGraphicsltem 578, 582, 588-592, 595, 597,
601,603,605,606
.
QGraphicsltemGroup 580, 597
QGraphicsLineltem 579, 592
QGraphicsOpacityEffect 600
QGraphicsPathltem 580, 592
QGraphicsPixmapltem 580, 592, 594, 595
QGraphicsPolygonltem 580, 592, 593, 594
QGraphicsProxyWidget 580
QGraphicsRectltem 578, 580, 592, 593
QGraphicsScene 578-584, 588, 589, 597
QGraphicsSceneDragDropEvent 604
QGraphicsSceneEvent 602, 603, 604
QGraphicsSceneHoverEvent 602, 603
QGraphicsSceneMouseEvent 601, 602
QGraphicsSceneWheeiEvent 602, 603
QGraphicsSimpleTextltem 580, 592, 595
QGraphicsSvgltem 592
QGraphicsTextltem 580, 592, 595, 596
QGraphicsView 578, 584, 585-587
QGraphicsWidget 581

QGridLayout 472, 473

QGroupBox 478, 479, 494


QHBoxLayout 469, 470
QHeaderView 541, 543, 545, 5~6
QHideEvent 445
Qlcon 419, 576
Qlmage 551,562,567,569,573,574
QlmageReader419,569
QlmageWriter 569
QlnputDialog 607, 618---Q21
QlntValidator 499
QltemSelection 548
QltemSe1ectionModel 547, 548
QKeyEvent 444, 454, 465, 601
QKeySequence 452, 454, 650.
QLabel366,423,452,474,489,492,651
QLCDNumber 517, 518
QLine 557
QLinearGradient 557
QLineEdit 495, 497, 619
QLineF 557
QListView 529, 539, 540, 620
QListWidget 536
QMainWindow 368,398,640,642,645,653,
658,659
QMatrix 568, 573, 587, 591
QMdiArea 640, 659---Q62
QMdiSubWindow 640,659,660,662,663
QMenu 644---Q48, 651, 656, 662, 663
QMenuBar 641, 644, 645
QMessageBox 607, 612---Q 16
QMimeData 461, 462-464, 604
QMimeSource 464
QModellildex 528-530, 532, 533, 536, 538540,542-544,547,548
QMouseEvent444,455,456,465,466
QMoveEvent 446
QMutex 392
QMutexLocker 392, 394
QObject 367, 369, 381, 398, 426, 430, 431,
433,439,465,489
QPaintDevice 367,398,551,562,570,572,
573,576
QPainter 551, 562, 563, 565-567, 569, 570,
572,573
QPainterPath 588
QPaintEvent 447
QPalette 420, 421
QPen 555, 556
QPersistentModellndex 529
QPicture 551, 562, 568
QPixmap 395, 396, 422, 423, 459, 551, 557,
562,566,567,569,570,573,576

QPiainTextEdit 500
QPoint 406,407,410
QPointF 407
QPolygon 558, 559
QPolygonF 559
QPrintDialog 607
QPrinter 502, 506, 551, 562
QPrintPreviewDialog 607
QProgressBar 518, 519
QProgressDialog 632, 633
QPushButton 366, 39\, 492, 493
QPyNu\IYariant 379
QRadiaiGradient 557
QRadioButton 494
QRect 406, 407, 410, 414
QRectF 407
QRegExp 550
QRegExpYalidator 499
QRegion 447
QResizeEvent 446
QScro\IArea 487, 522
QScroiiar 487, 488, 522
QSemaphore 395
QShoncut 453
QShoncutEvent 452
QShowEvent 445
QSize 390, 40~08, 41
QSizeF 407
QSizePolicy 477
QSiider 519,520,521
QSonFilterProxyModel 549
QSpinBox 512,513
QSplashScreen 395, 396, 400
QSplitter 485, 486
QStackedLayout 475, 476
QStackedWidget 476
QStandardltem 530-535
QStandardltemMode\ 530, 533
QStatusBar 641,658,659
QStatusTipEvent 651
QString 377
QStringList 378
QStringListModel 529, 530
QStyle 419, 577
QSystemTraylcon 663, 664
Qt377
QT_ VERSION_STR 362
QTa\eYiew 530, 536, 540, 545
QTa\eWidget 536
QTabWidget 480-483,643,661
QtCore 365, 368, 377,392

685
QtCore4.dll 361
QtDeclarative 377
QtDesigner 3 77
QTextiock 507
QTextBrowser 511, 512
QTextCharFormat 505, 517
QTextCursor 506, 508-51
QTextDocument 501,505-507
QTextDocumentFragment 51
QTextEdit 500, 502-505, 508, 509, 511
QTextOption 503, 565
QTextStream 379
QtGui 365, 366, 368, 377
QtGui4.dll 36\
QtHelp 377
QThread 381-384,395
QTime 379,514,515
QTimeEdit 5 14, 5 15
QTimer 440-442
QTimerEvent 439
QtMultimedia 377
QtNetwork 377
QTooiar 641, 653-655
QTooiox 484
QTooiutton 655, 656
QtOpenGL 377
QTransform 59\
QTreeYiew 530, 536, 543-545
QTreeWidget 536
QtScript 377
QtScriptTools 377
QtSq\377
QtSvg 377
QtTest 377
QtWebKit 377,512
QtXml377
QtXm\Patterns 377
Query 341
Question 613, 616
Queue 388, 391
QueuedConnection 384, 429, 430
quit() 367, 379, 386, 424, 428
quote() 345, 346
quote_from _ bytes() 346
quote_plus() 344, 345
quoteattr() 348
QUrl379
QValidator 499, 525
QVariant 378, 379
QVBoxLayout 469, 470
QWaitCondition 395
QWheelEvent 457,458

686

QWidget 366-369,391,398,399,415-417,
419,420,424,429,432,447,449,450,452,
457,458,463,469,471,477,479,489,493,
539,551,562,572,609,646,654
QWindowStateChangeEvent 445
QWizard 633, 635, 636, 637
QWizardPage 633---635, 637, 639

R
R 278
radians() 73
Raise 256, 257, 258
raise_() 609
Raised 480
randint() 74
random() 73-75, 148, 150
randrange() 74
range() 63, 64, 74, 140, 150
rangeChanged() 520
raw_input() 32
Re 114, 124
read()266,272,274,349,354
readline() 267, 274, 354
readlines() 267, 275, 354
ReadOnly 625
reason() 351, 450
rect() 402,447,571, 574,593,594
Recursive 392
red() 552, 553
redF() 553
redo() 497,501,505,510
redoA vailaie() 502, 507
RedoStack 506
reduce() 144
Referer 353
region() 447
register_ adapter() 332
register_converter() 334
registerEventype() 442, 466
registerField() 634, 635, 637
reject() 608, 610, 625
rejected() 609,612,619,624
RejectRole 611, 612, 614
released() 493
releaseKeyboard() 450, 455
releaseMouse() 456
releaseShortcut() 452
reload() 223, 224, 511
remove() 111, 146, 171, 279, 559
removeAction() 647, 652, 654
removeButton() 612, 615

removeColumn() 534
removeColumns() 531, 534
removeDockWidget() 642
removeEventFilter() 466
removeFonnat() 463
removeFromGroup() 597
removeltem()484, 524, 580
removePage() 634
removeRow() 534
removeRows() 530, 531, 534
removeSceneEventFilter() 605
removeSelectedText() 51
removeSubWindow() 660
removeTab() 482
removeTooiBar() 641
removeTooiBarBreak() 642
removeWidget() 470,476,659
rename() 279
render() 583, 588
repaint() 447,448,551
repeat() 154, 196
replace() 1 1, 182, 184, 187
repr() 91, 94, 239
Request349,354,356
reset() 358,519,611,613,633
resetCachedContent() 585
resetMatrix() 587, 591
ResetRole 611, 614
resetransform() 591
resize() 366, 401, 443, 468
resizeColumnsToContents() 541
resizeColumnToContents() 541, 543
resizeEvent() 446
resizeRowsToContents() 541
resizeRowToContents() 541
resizeSection() 545
ResizeToContents 545
restart() 634
restore() 568
RestoreDefaults 611, 613
restoreDockWidget() 644
restoreGeometry() 644
restoreOverrideCursor() 459
restoreState() 486, 546, 625, 644
Result 358, 608
retranslateUi() 375
retrieveData() 463
Retry 611,613
Retum 197, 198
retumPressed() 497
reverse() 111, 148
reversed() 148

RFC 2616 353


rfind() 99
Rgb 555
rgb() 553, 574, 515
rgba() 553, 574, 515
RichText490,615,635
Right 509
RightArrow 656
RightButton 456, 458
RightDockWidgetArea 642, 643, 657
RightoLeft 471
Rightoo\arArea 641, 654
rindex() 100
rjust() 89
rrndir() 290, 291
rrntree() 291
rollback() 327, 339
rootlndex() 536
rotate() 568, 587, 590
rotation() 591
round() 71, 239
RoundCap 556
Rounded 483, 643, 661
RoundJoin 556
row() 529, 533
row_factory 325, 326
rowcount 323
rowCount() 473, 530, 533
rowHeight() 541, 543
row1ntersectsSelection() 54 7
Rows 548
rowSpan() 54\
rpartition() 96
rsplit() 95
rstrip() 94
RubberBandDrag 585
RubberBandMove 663
RubberBandResize 663
run() 381,383,384,386,388,391

s
sample() 75, 149, \50
Saturday 517
SA TURDA \90
save()568--570,574,610,613
SaveAI1610, 613
saveGeometry() 644
saveState() 486, 546, 625, 644
ScalaeFonts 527
scale() 408, 568, 587, 591
scaled() 571,575

687

scaledToHeight() 572, 576


sca\edToWidth() 572, 515
scene() 584, 589
sceneBoundingRect() 589
sceneEvent() 605
sceneEventFilter() 605
sceneMatrix() 591
scenePos() 589,602-604
sceneRect() 579, 584
sceneRectChanged() 584
sceneTransforrn() 591
scheme 341
ScientificNotation 499
screenGeometry() 405
screenPos() 602-604
ScrollBarAiwaysOff 488
ScrollBarAlwaysOn 488
ScrollBarAsNeeded 488
ScrollHandDrag 585
scrollTo() 538
scrollToBottom() 538
scrollToTop() 538
SD\- 640
search() \23, 124, \26
Second 183, 185, 186
Seconds 178, 179
SecondSection 515
sectionAt() 515
sectionC\icked() 546
sectionCount() .515
sectionDou\eC\icked() 54 7
sectionMoved() 54 7
sectionPressed() 546
sectionResized() 547
sectionsHidden() 546
sectionSize() 545
sectionText() 515
seed() 74
seek() 269, 273
SEEK_CUR 269,272
SEEK_END 269, 272
SEEK_SE 269,272
select() 51 , 548
selectAII() 496,501,513,537
selectColumn() 542
SelectColumns 537
SelectCurrent 548
selected() 653
SelectedCiicked 537
selectedColumns() 548
selectedDate() 516
selectedfiles() 625

688

selectedlndexes() 540, 542, 544, 547


selectedltems() 583
selectedRows() 548
selectedText() 491,496,510
selectFile() 625
Selection 465
selection() 51 , 548
selectionArea() 583
selectionChanged() 497, 502, 517, 549, 584
selectionEnd() 51
selectionModel() 537, 547
selectionStart() 491, 496, 51
Selectltems 537
selectRow() 542
SelectRows 537
Self229
sendEvent() 466
Sep 260,282
Server 353
set() 39, 167, 171
setAcceptDrops() 463, 603
setAccepted() 442
setAcceptedMouseButtons() 601
setAcceptHoverEvents() 603
setAcceptMode() 624
setAcceptRichText() 501
setActionGroup() 651
setActivationOrder() 661
setActiveAction() 645, 647
setActiveSubWindow() 660
setActiveWindow() 581
setAiignment() 369, 479, 487, 490, 496, 505,
513,585
setAIIowedAreas() 653, 654, 657
setAipha() 553
setAiphaF() 553
setA lternatingRowColors() 536
setAnimated() 544, 642
setapi() 377
setArrowType() 656
setattr() 229
setAttribute() 418, 425, 456
setAutoC1ose() 633
setAutoCompletion() 525
setA utoCompletionCaseSensitivity() 525
setAutoDefault() 493, 610
setAutoExclusive() 493
.
setAutoFiiiBackground() 420, 422
setAutoFormatting() 503
setAutoRaise() 656
setAutoRepeat() 492, 651
setAutoReset() 633

setAutoScroll() 538
setAutoScroiiMargin() 538
setackground() 535, 661
setBackgroundBrush() 579, 585
setar() 632
setaseSize() 402
setBatchSize() 540
setBinMode() 518
set81ue() 553
set81ueF() 553
setBiurRadius() 598, 599
setBold() 560
setottom() 411
setBottomLeft() 411
setBottomRight() 411
setBrush() 421, 556, 562, 593
setBspTreeDepth() 579
setBuddy() 452, 474, 490
setButton() 635
setuttonLayout() 636
setButtonSymbols() 512
setuttonText() 636, 637
setCacheMode 585
setCalendarPopup() 515
setCancelButton() 632
setCanceiuttonText() 619, 633
setCapStyle() 556
setCascadingSectionResizes() 545
setCaseSensitivity() 506
setCenterButtons() 612
setCentraiWidget() 640, 659
setCheckaie() 479, 493, 535, 650
setChecked() 479, 493-495, 650
setCheckState() 494, 535
setChild() 533
setChildrenCollapsile() 486
setCiickaie() 546
setCmyk() 553
setCmykF() 554
setCollapsiie() 486
setColor() 420, 421, 556, 557, 598, 599
setColumnCount() 530, 533
setCo1umnHidden() 541, 543
setColumnMinimumWidth() 473
setColumnStretch() 473
setColumnWidth() 541,543
setComboBoxEditaie() 620
setComboBox1tems() 620
setCommitPage() 638
setCompleter() 495, 525
setContextMenu() 663
setCoords() 411

setCorner() 643
setCornerButtonEnaed()

542
setCurrentCharFormat() 505
setCurrentFont() 504, 527
setCurrentlndex() 476, 483, 485, 524, 536, 548
setCurrentPage() 516
setCurrentSection() 5 15
setCurrentSectionlndex() 515
setCurrentWidget() 476, 483, 485
setCursor() 458, 590
setCursorPosition() 496
setCursorWidth() 503
setData() 462, 530, 532, 535, 651
setDate() 514
setDateRange() 515, 516
setDateTextFormat() 517
setDateTime() 514
setDateTimeRange() 515
setDecimals() 513
setDecMode() 518
setdefault() 162, 165, 289
setDefault() 493, 61
setDefaultAction() 647, 656
setDefaultAiignment() 546
setDefaultButton() 615
setDefaultFont() 506
setDefaultProperty() 638
setDefaultSectionSize() 545
setDefaultStyleSheet() 507
setDefaultSuffix() 625
setDefaultTextColor() 596
setDefaultUp() 645
setDetailedText() 614
setDigitCount() 518
setDirection() 471
setDirectory() 625
setDisaedO 371,384,432,651,653
setDisplayFormat() 515
setDockNestingEnaed() 643
setDockOptions() 642
setDocument() 505, 596
setDocumentMargin() 507
setDocumentMode() 483
setDocumentTitle() 500
setDoueCiicklnterva\() 455
setDouieDecimals() 620
setDoueMaximum() 620
setDoueMinimum() 620
setDoueRange() 620
setDoueValue() 620
setDown() 493
setDragCursor() 461

689
setDragDropMode() 538
setDragEnaed() 496, 535, 538
setDragMode() 585
setDropAction() 463, 464, 604
setDropEnaed() 535
setDroplndicatorShown() 538
setDuplicatesEnaed() 525
setDynamicSortFilter() 550
setEchoMode() 495, 496
setEditae() 524, 535
setEditText() 524
setEditriggers() 53 7
setE\ideMode() 482
setEnaed() 432, 493, 535, 590, 598, 645,
647,65.1,653
setEscapeButton() 615
setExclusive() 652
setExpanded() 544
setExtension() 608
setFamily() 560
setFeatures() 65 7
setField() 634, 638
setFieldGrowthPolicy() 4 75
setFileMode() 624
setFilterCaseSensitivity() 550
setFilterFixedString() 549
setFilterKeyColumn() 550
setFilterRegExp() 550
setFilterRole() 550
setFiltersChildEvents() 605
setFilterWildcard() 550
setFina\Page() 638
setFirstDayOfWeek() 516
setfirstweekday() 190, 192
setFixedHeight() 401
setFixedSize() 401
setFixedWidth() 401
setFiag() 582, 589
setFiags() 535, 589
setFiat() 479, 493
setF\oatae() 653, 55
setFioating() 657
setFiow() 540
setFocus() 449, 450, 582, 590
setFocus\tem() 582
setFocusPolicy() 450, 455
setFocusProxy() 449, 601
setFont() 535, 560, 579, 595, 596, 651
setFontFamily() 504
setFontFilters() 527
setFontltalic() 504
setFontPointSize() 504

690

setFontUnderline() 504
setFontWeight() 504
setForeground() 535
setFpregroundBrush() 579, 585
setFormAiignment() 475
setFrame() 496, 513,525
setFrameShadow() 480
setFrameShape() 480
setFrameStyle() 480
setGeometry() 401, 404, 468
setGraphicsEffect() 597
setGreen() 553
setGridSize() 539
setGridStyle() 542
setGridVisiie() 517
setGroup() 597
setHandleWidth() 486
setHeader() 545
setHeaderData() 532
setHeaderHidden() 543
setHeaderTextFormat() 517
setHeight() 408, 411
setHeightForWidth() 478
setHexMode() 518
setHighlightSections() 546
setHistory() 625
setHorizontalHeader() 545
setHorizonta1HeaderFormat()516
setHorizontaiHeaderltem() 532
setHorizontaiHeaderLabels() 532
setHorizontaiPolicy() 477
setHorizontaiScroiiBarPolicy() 488
setHorizontaiSpacing() 473,475
setHorizontaiStretch{) 477
setHotSpot() 461
setHsv() 554
setHsvF() 554
setHtml() 462, 500, 505, 596
setlcon() 492,535,614,647,649,663
setlconPixmap() 614
setlconSize() 492,525,537,641,655
setlcon VisiielnMenu() 649
setlmageData() 462
setlndent() 491
setlndentation() 544
setlndexWidget() 536
setlnformativeText() 614
setlnputMask() 498
setlnputMode() 619
setlnsertPolicy() 524
setlnteractive() 585
setlnterval() 440

setlntMaximum() 620
setlntMinimum() 620
setlntRange() 620
setlntStep() 620
setlntValue() 620
setlnvertedAppearance() 519, 520
setlnvertedControls() 520
setltalic() 560
setltem() 531
setltemData() 524
setltemEnaied() 485
setltemlcon() 485, 524
setltemlndexMethod() 579
setltemsExpa:ndaie() 544
setltemText() 485, 524
setltemTooiTip() 485
setJoinStyle() 556
setKeepPositionOnlnsert() 51
setKeyboardPageStep() 662
setKeyboardSingleStep() 662
setLabel() 632
setLabeiAiignment() 475
setLabeiext() 619, 625, 633
setLayout() 367, 429, 470, 472, 473, 476, 478
setLayoutDirection() 471
setLayoutMode() 540
setLeft() 41 1
setLine() 558, 593
setLineWidth() 480
setLineWrapColumnOrWidth() 503
setLineWrapMode() 503
setlocale() 97
setMargin() 472, 473, 475, 491
setMask() 423, 571
setMatrix() 568, 587, 591
setMaxCount() 525
setMaximum() 513, 519, 520, 633
setMaximumBiockCount() 507
setMaximumDate() 515,516
setMaximumDateTime() 515
setMaximumHeight() 402
setMaximumSize() 402
setMaximumTime() 51 5
setMaximum Width() 402
setMaxLength() 496
setMaxVisiieltems() 525
setMenu() 494, 651, 656
setMenuBar() 641, 645
setMenu Widget() 641
setMidLineWidth() 480
setMimeData() 461, 462, 465
setMinimum() 513, 519, 520, 633

setMinimumContentsLength() 525
setMinimumDate() 515, 516
setMinimumDateTime() 515
setMinimumDuration() 633
setMinimumHeight() 402
setMinimumSectionSize() 545
setMinimumSize() 401
setMinimumTime() 515
setMinimumWidth() 402
setModa\() 609
setMode() 518
setMode\() 529, 530, 539, 541, 543
setMode\Column() 539
setMouseTracking() 457, 539
setMova\e() 483, 546, 654
setMovement() 539
setMovie() 491
setNamedColor() 552
setNameFilter() 625
setNameFilterDetailsVisi\e() 625
setNameFilters() 625
setNavigationBarVisi\e() 516
setNotation() 499
setNotchesVisi\e() 521
setNotchTarget() 52\
setNum() 490
setObjectName() 644
setOctMode() 518
setOffset() 595, 598
setOkButtonText() 619
setOpacity() 589, 600
setOpacityMask() 600
setOpaqueResize() 486
setOpenExterna\Links() 490, 596
setOpenLinks() 511
setOption() 620, 624, 636, 661, 662
setOptions() 620, 625, 637
setOrientation() 486, 519, 520, 609, 61 1
setOverline() 561
setOverrideCursor() 459
setOverwriteMode() 503
setPJ() 558
setP2() 558
setPage() 634
setPageStep() 520
setPalette() 420, 422
setParent() 399
setParentltem() 59\
setPen() 562, 593
setPicture() 491
setPixel() 575
setPixe\Size() 560

691

setPixmap() 396, 423, 461, 490, 595, 636, 637


setP\aceholderText() 496
setP\ainText() 500, 505, 596
setPoint() 559
setPoints() 557, 559
setPointSize() 560
setPointSizeF() 560
setPolygon() 594
setPopupMode() 656
setPos() 459, 588
setPosition() 509
setPrefix() 513
setPriority() 382, 651
setQuitOnLastWindowC\osed() 379
setRange() 513,5\9,520,633
setReadOnly() 496, 503, 513, 625
setRect() 41 \, 593, 594
setRed() 553
setRedF() 553
setRenderHint() 565, 566
setResizeMode() 539, 545
setResu\t() 608
setRgb() 552, 553
setRgba() 553
setRgbF() 553
setRight() 4 1 1
setRootlndex() 536
setRootlsDecorated() 544
setRotation() 591
setRowCount() 530, 533
setRowHeight() 541
setRowidden() 540, 541, 543
setRowMinimumHeight() 473
setRowStretch() 473
setRowWrapPolicy() 475
setRubberBandSe\ectionMode() 585
setScale() 591
setScaledContents() 491
setScene() 584
setSceneRect() 579, 584
setSectionHidden() 546
setSegmentStyle() 518
setSelecta\e() 535
setSelected() 582, 590
setSelectedDate() 516
setSelectedSection() 51 5
setSelection() 491, 496
setSe\ectionArea() 582
setSelectionBehavior() 537
setSelectionMode() 517, 537
setSelectionMode\() 537, 547
setSelectionRectVisie() 540

692
setSeparator() 649
setSeparatorsCollapsible() 648
setShapeMode() 595
setShortcut() 492, 650
setShortcutContext() 650
setShortcutEnabled() 452
setShortcuts() 650
setShowGrid() 542
setSidebarUrls() 625
setSingleShot() 441
setSingleStep() 513, 520
setSize() 41 1
setSizeAdjustPolicy() 525
setSizeGripEnabled() 609, 659
setSizePolicy() 477
setSizes() 486
setSiiderPosition() 520
setSmallDecimalPoint() 518
setSortCaseSensitivity() 549
setSortingEnabled() 542, 544, 549
setSortLocaleA ware() 549
setSortRole() 533, 549
setSource() 51 1
setSourceModel() 549
setSpacing() 472, 473, 475, 540
setSpan() 541
setSpanAngle() 594
setSpeciaiValueText() 513
setStackingMode() 476
setStandardButtons() 611, 615
setStartAngle() 594
setStartDragDistance() 460
setStartDragTime() 460
setStartld() 634
setStatusBar() 641, 658
setStatusTip() 650, 658
setStickyFocus() 582
setStrength() 599
setStretchFactor() 486
setStretchLastSection() 545
setStrikeOut() 561
setStringList() 530
setStyle() 556, 557
setStyleSheet() 420
setSubTitle() 637
setSubTitleFormat() 635
setSuffix() 513
setSystemMenu() 662
setabChangesFocus() 503, 596
setabEnabled() 483
setTablcon() 482
setTabKeyNavigation() 538

setTabOrder() 450
setTabPosition() 482, 643, 661
setabsClosable() 483
setTabShape() 482,643,661
setabStopWidth() 503
setTabText() 482
setTabToolTip() 483
setTab WhatsThis() 483
setTearOffEnabledO 647
setter() 246
setext() 371, 384, 388, 391, 462, 465, 489,
. 492,496,498,500,535,595,614,649
setTextAiignment() 535
setTextBackgroundColor() 504
setTextColor() 504
setTextCursor() 508, 596
setTextDirection() 519
setTextEchoMode() 619,621
setTextElideMode() 537
setTextFormat() 490, 614
setextlnteractionFiags() 491, 502, 596
setexture() 557
setexturelmage() 557
setextValue() 619
setTextVisible() 519
setTextWidth() 596
setTicklnterval() 521
setTickPosition() 521
setTime() 514
setTimeRange() 515
setimeSpec() 515
setitle() 479, 637, 647
setitleBarWidget() 657
setTitleFormat() 635
setTooluttonStyle() 641, 655, 656
setToolTip() 424, 535, 590, 650, 663
setTop() 411
setTopLeft() 411
setTopRight() 411
setTracking() 520
setTransform() 59\
setTransformationMode() 595
setTransformOriginPoint() 591
setTristate() 494, 535
setUnderline() 561
setUndoRedoEnabled() 501, 506
setUniformltemSizes() 540
setUniformRowHeights() 543
setUpdatesEnabled() 447
setupUi() 374, 375, 376
setUrls() 462
setUsesScroiiButtons() 483

693

setValidator() 499, 525


setValue() 513,519,520,632
setVerticaiHeader() 545
setVerticaiHeaderFormat() 517
setVerticaiHeaderltem() 532
setVerticaiHeaderLabels() 532
setVerticaiPolicy() 477
setVerticaiScroiiBarPolicy() 488
setVerticaiSpacing() 473,475
setVerticaiStretch() 4 77
setViewMode() 539, 624, 661
setViewport() 567
setViewportMargins() 488
setVisiie() 399, 590, 609, 61 , 645, 647, 651,
653,663
setWeekdayTextFormat() 517
setWeight() 560
setWhatsThis() 424, 535, 650
setWidget() 487, 657, 662
setWidgetResizaie() 487
setWidth() 408, 411, 556
setWidthF() 556
setWindow() 567
setWindowFiags() 399
setWindowlcon() 419
setWindowModality() 417, 609
setWindowOpacity() 416
setWindowState() 415
setWindowTitle() 3(;6, 399,581,614
setWizardStyle() 635
setWordWrap() 490, 540, 542, 544
setWordWrapMode() 503
setWrapping() 513, 521 1 540
setX() 407,411,589
setXOffset() 598
setY() 407,411,589
setYOffset() 599
setZValue() 589
shal() 112
sha224() 112
sha256() 112
sha3 84() 1 12
sha512() 112
shape() 588
shear() 568, 587, 591
Sheet 400
Shelve 286, 288, 293
ShiftModifier 454
Shortcut452
ShortcutFocusReason 449
shortcutld() 452
ShortDayNames 517

Show 443
show()396,399,405,590.609.663
ShowAiphaChannel 629
showColumn() 542, 543
SlwDirsOnly 624
showEvent() 445
showExtension() 608
showFullScreen() 415
showMaximized() 415
showMenu() 494, 656
showMessage() 396, 632, 6S.8, 664
showMinimized() 415
showNextMonth() 516
showNextYear() 516
showNormal() 415
showPopup() 525
showPreviousMonth() 516
showPrevious Year() 516
showRow() 541
showSection() 546
showSelectedDate() 516
showShaded() 662
showStatusText() 651
showSystemMenu() 662
showToday() 516
ShowToParent 443
shuffle() 75, 148
Shutil 278, 291
siiing() 529
SIGNAL() 426, 433
signalsBiocked() 430
sin() 72
SingleLetterDayNames 517
Sing\ePass 540
SingleSelection 517, 537
singleShot() 442
Sip 377
size() 402, 412, 446, 559, 571, 574
SizeAIICursor 458
SizeBDiagCursor 458
SizeFDiagCursor 458
sizeHint() 402, 475, 477
SizeHintRole 528
SizeHorCursor 458
sizePolicy() 477
sizes() 486
SizeVerCursor 458
sleep() 177, 379, 383, 384
SliderMove 520
sliderMoved() 521
SliderNoAction 520
SliderPageStepAdd 520

694
SliderPageStepSub 520
sliderPosition() 520
sliderPressed() 521
sliderReleased() 521
SliderSingleStepAdd 520
SliderSingleStepSub 520
SliderToMaximum 520
SliderToMinimum 520
SLOT()428
smoothSizes() 56\
SmoothTransformation 572, 575, 595
Snap 539
SolidLine 542, 555
SolidPattem 421, 557
sort() 149, \50, \63,206,530,533,549
sortByColumn() 542, 544
sortChirdren() 536
sorted() 63, 150, \63
source() 461, 464, 511, 605
sourceChanged() 512
sourceModel() 549
South 482, 643, 661
span() 126
spanAngle() 594
spec() 555
SplashScreen 400
split() 95, 130, 131, 283
splitDockWidget() 644
splitdrive() 283
splitext() 283
SplitHCursor 458
splitlines() 95
SplitResult 342
splitterMoved() 487
SplitVCursor 458
spontaneous() 442
SQL 293
SQLite 293
Sqlite_ version 3\8
Sqlite_version _info 318
Sqlite3 293, 318
sqrt() 73
SquareCap 556
StackAII 476
stackingMode() 476
StackingOrder 660
StackOne 476
StandardNotation 499
starmap() 157
start() 126,381,384,386,391,440,461
startAngle() 594
startDragDistance() 460

startDragTime() 460
started() 382, 384
startld() 634
StartOffilock 508
StartOfLine 508
StartOfWord 508
startswith() 100
startTimer() 439, 440, 441
Stat 278
stat() 280
Stat result 280
stateChanged() 495
Static 539
Status '351
statusBar() 641, 658
StatusTip 651
statusTip() 650
StatusTipRole 527
Stderr 268, 283
Stdin 3\, 268, 283, 284
Stdout29,268,270,283,285
step() 331
stepBy() 513
stepUp() 513
stickyFocus() 582
stop() 440
Stoplteration 65, 207, 238, 256, 268, 275,
324,355
SU\)38,45, 77,84,9\,94,\5\,239,263,327
strength() 599
strengthChanged() 600
Stretch 545, 636
strftime() 175-177-, 182, 184, 188,216
strikeOut() 561
String 125
String\0 273, 276
stringList() 530
strip() 94
StrongFocus 450
strptime() 175, 176, 186
struct_time 173-176, 182, 187, 194
StyledPanel 480
styles() 561
sub() 128, 129
subn() 130
subTitle() 637
SubWindow 400
subWindowActivated() 662
sub WindowList() 660, 661
SubWindowView 661
sum() 72, 196
Sunday 190, 517

695

Sunken 480
super() 233, 234
supportedlmageFormats() 419, 569
supportsMessages() 664
SvgMiterJoin 556
swapcase() 98
swapSections() 546
symmetric_difference() 169, 172
symmetric_ difference_ update() 169
SyntaxError 256
sys 31, 42, 219, 249, 253
sys.argv 32
sys.path 222
sys.stdin 3 1
sys.stdout 31
systemMenu() 662

TabbedView 661
tabCioseRequested() 483
TabFocus 450
TabFocusReason 449
taifiedDockWidgets() 644
taifyDockWidget() 644
tabPosition() 643, 661
tabShape() 643, 661
tabStopWidth() 503
tabText() 482
takeChild() 534
takeColumn() 531, 534
takeltem() 531
takeRow() 531, 534
takewhile() 156
takeWidget() 487
tan() 72
target() 461
targetChanged() 461
TargetMoveAction 460
task_done() 389
tee() 158
tell() 269, 273
terminate() 386
testOption() 662, 663
text() 454, 462, 465, 490, 492, 496, 51 3, 519,.
535,595,649
Text_factory 327, 332
TextAiignmentRole 527
TextAntialiasing 566
textBackgroundColor() 505
Textrowserlnteraction 491, 503
TextCalendar 189, 190

textChanged() 497, 502


textColor() 504
textCursor() 508, 596
TextDontClip 565
TextEditaie 491, 502
textEdited() 498
TextEditorlnteraction 491, 502
TextExpandTabs 565
TextHideMnemonic 565
Textlnput 619, 620
TextSelectaleByKeyboard 491, 502
TextSelectaieByMouse 491, 502
TextShowMnemonic 565
TextSingleLine 565
textValue() 620
textValueChanged() 620
textValueSelected() 620
textWidth() 596
TextWordWrap 565
TextWrapAnywhere 565
Threading 395
Thursday 517
THURSDA 190
TicksAbove 521
Ticks8e1ow 521
TicksBothSides 521
TicksLeft 521
TicksRight 521
ti1eSubWindows() 661
Time 173, 175, 177, 178, 11!2-184,
186-188, 194,216,217,379,514,515
time() 173, 187,515
timeChanged() 515
TimeCriticaiPriority 382
timede1ta 178, 179
timegm() 194
timeit() 173, 195, 196
timeout() 440
Timer 195, 443
timerEvent() 439
timerld() 439, 441
timetup1e() 182, 187
timetz() 187
tip() 651
title() 98, 637, 647
titleBarWidget() 657
tobytes() 276
toCmyk() 555
today() 180, 185
toggle() 493, 548, 652
ToggleCurrent 548
toggled() 479, 493-495, 652

696

toggleViewAction() 655, 657


toHsl() 555
toHsv() 555
toHtml() 501, 505, 51 , 596
tolmage() 571
tolist() 276
1400
tooiarArea()

641
642

tooiarBreak()

TooiuttonFollowStyle

641, 655
641, 655
tooiuttonStyle() 641, 655, 656
TooiuttonTextesidelcon 641, 655
Too\uttonTextOnly 641, 655
TooiButtonTextUnderlcon 641, 655
tooiTip() 400, 424, 650, 663
TooiTipRole 524, 527
toordinal() 181, 182, 186, 188
top() 412
TopDockWidgetArea 642, 643, 657
toPiainText() 500, 505, 51 , 596
topLeft() 4 13
TopLeftCorner 643
topLeveiChanged() 655, 658
topLevelltem() 591
topRight() 413
TopRightCorner 643
TopToBottom 472,519,540
TopTooiBarArea 641, 654
toPyDate() 514
toPyDateTime() 514
toPyObject() 378
toPyTime() 514
toRgb() 555
total_ seconds() 179
traceback 249
transform() 591
transformed() 572, 573, 576
translate() 101,412,568,587,590
translated() 412
Transparent 552
transpose() 409
Triangular 483, 643, 661
trigger() 652, 664
triggered() 645, 648, 652, 653, 656
True 38,55
truncate() 268, 275
try 248
tryLock() 392
Tuesday 190, 517
tuple() 38, 46, 151
type() 39, 43, 443
TooiuttonlconOnly

TypeError96, 146, 151,256,379


typeNan.1e() 379
tzinfo 178, 183-187
tzname() 184, 188

u
Uic 373
UliPad 14
UnboundLocaiError 211, 256
Unchecked 494, 528, 535
underline() 561
undo()497,501,505,510
UndoAndRedoStacks 506
undoA vailaie() 502, 507
undoCommandAdded() 507
UndoStack 506
unescape() 348
ungrabKeyboard() 590, 601
ungrabMouse() 590, 602
UNICODE 115, 119
UnicodeDecodeError 45, 78, 256
UnicodeEncodeError 105, 109,256
uniform() 74
union() 168, 172
UniqueConnection 430
unite() 414
united() 414
Universa\Detector 358
Unknown 664
unlink() 279
unlock() 392, 394
Unpickler 287
unquote() 346
unquote_plus() 346
unquote_ to_ bytes() 346
unsetCursor() 459, 590
Up 508
UpArrow 656
UpArrowCursor 458
update() 112, 166, 168,289,447,448,551,
584,592,598
updateScene() 588
updateSceneRect() 588
UpDownArrows 512
upper() 98
urlencode() 344
urljoin() 347
urllib.parse ~40, 343-345, 347
urllib.request 340, 354
urlopen() 354, 356
urlparse() 340-342

urls() 462
urlsplit() 342
urlunparse() 342
urlunsplit() 343
URL-apec 340
UseListViewForComboBoxltems 620
User 444
User-Agent 353
Username 342
UserRole 528
usleep() 384
UTC 515
utcfromtimestamp() 185
utcnow() 185
utcoffset() 184, 188
utctimetuple() 187
utime() 281

v
validateCurrentPage() 634
validatePage() 639
value() 513, 518-520, 554, 633
valueChanged() 513,519-521
ValueError65,99, 100,111,146,147,153,
175, 180, 183, 185, 186, 247,256, 344
vafuef() 555
values() 164, 288, 352
vars() 213
VERBOSE 115
Version 351
Vertica1458,486,519, 520,522,532,545,
603,609--611,642,644
verticaiHeader() 541, 545
verticaiHeaderltem() 532
verticaiScrol\Bar() 488
VerticaiTabs 643
viewMode() 661
viewport() 488, 567
viewportEntered() 539
views() 583
visibllityChanged() 655, 658
visitedPages() 634
visuallndex() 546
VLine 480

w
w 278
W_ DeleteOnCiose 418, 425, 660
W_ NoMousePropagatiqn 456
wait() 386

697
WaitCursor 458, 459
walk() 290, 291
Warning 337,613,664
wasCanceled() 633
WatermarkPixmap 636
Wednesday 190,517
weekday() 182, 188, 194
Weeks 179
weight() 560
West 482, 643, 661
whatsThis() 424, 650
W.hatsThisCursor 458
WhatsThisRole 527
Whee1443
whee\Event() 457, 602
Wheelfocus 450
while 26, 66--68, 140, 196
White 396, 552
Widget 399
widget() 476, 483, 485, 487, 657, 662
widgetForAction() 654, 655
widgetRemoved() 476,477
WidgetShortcut 452, 650
WidgetWidth 503
WidgetWithChildrenShortcut 452, 650
width()402,405,408,412,561,571,574,579
Window 399, 420, 567
WindowActivate 443
WindowActive 415
WindowBiocked 444
WindowCioseButtonHint 401
WindowContextHelpButtonHint 401
WindowDeactivate 443
windowflags() 401
WindowFul\Screen 415
WindowMaximizeButtonHint 400
WindowMaximized 41 5
WindowMinimizeButtonHint 400
WindowMinimized 415
WindowMinMaxButtonsHint 401
WindowModal417, 418,'609
windowModality() 417, 609
WindowNoState 415
windowOpacity() 417
WindowsError 279-281
WindowShortcut 452, 650
windowState() 415
WindowStateChange 444, 445
windowStateChanged() 663
WindowStaysOnBottomHint 401
WindowStaysOnTopHint 396,401
WindowSystemMenuHint 400

698

WindowText 420
WindowTitleHint 400
windowType() 400
WindowUn\ocked 444
winld() 572
WinPanel 480
with 252-254, 339, 394, 395
wizard() 637
WordLeft 508
WordRight 509
WordUnderCursor 51
WordWrap 503
WrapAI\Rows 475
WrapAnywhere 503
WrapAtWordBoundaryOrAnywhere 503
WrapLongRows 475
write() 3\, 265,,272, 273
writelines() 266, 274

xml.sax.saxutils 347
xOffset() 598

()404,407,412,455,458,589,648
\()

558
558
Year \81, \86
YearSection 515
yearShown() 5 \6
Yel\ow 552, 554
yellowF() 554
Yes 6\0,6\3
YesRole 6\1,612,614
YesToAI\610, 6\3
Yield 206
yOffset() 599
2()

()404,407,412,455,458,589,648
278
xl() 558
2() 558
XButton 1 456
XButton2 456

ZeroDivisionError 249, 255, 256


zfill() 89
zip() 142, 143, 160
zip_Iongest() 157
zoomln() 501
zoomOut() 501
zValue() 589

322

3\

283

173
29

172
166
140

173

"\73

283
26

141

175
246

699

232

41, 44

301

119

228
312

33

36
23, 25
n 357
27
231
132, 151

3
n

301

"

301
305
308

306
306
306

303

\53
\52

\51

152

307

307
306
307

97

303

n n
n n

24, 32
177

n n

277

305

\53

\52
\52

304

36

132, \52, 312

n n

247
256

254
250

256

285

167
frozenset 171
set 167
172
200,216

n n

n n

226

223

n n

n n

232

234

291

277
281

290

290
260, 289
290

303

-
n

217

222

\89
HTML 191
190
289
290

226

216
from 219
import 216

(JJG) 228
243

219

217

700

(JJG)

(.)

40

246
232

228
228

231
242
234

232

228
239
244
0 !! 245
229
229
' 229
236
242
48
break 67
continue 67
for 61
if... else 58, 59, 61
in 56
is 56
pass 197
while 66
50

57
48

239

53

l!

51
139

138
151
132
\38

150

\37

277
41
41
42

25

114

51

120

128
119

118

116
120

56
55
40

136

138

127
123

130
115

114

52

283

27

131

24

209

247

247

426
159

224

36
21
21
47

247

166
166
163

163
161

161

159
164

162, 164

164

701

163, 165

367

426

n
n

23

81

132

nn

95
83
77

82

76

84

81

102

94

84, 90

94
112
79

24

148

140

144
n 150
136
147
147
139
n 139
n 148
n 148
n n 135
n 147
n n 135
n 151
n 138
132
149
137
146
82, 137
76
83, 94
28, 34, 79
1 1
98
98
112
83
94
80
n 81
n 83
n 84
n 99

304

295
317

260

38

44

43

303

PyQt 361
Python 17

n n

259

280
268
265, 272
n 265, 272
n 278
268
259,271

n n

n n

112

259

260

279
279
269

269

277

279

259

280
280

263

281
279

702
(.)

286

279
266, 272
209
197

205,211

198

215

213

206
207

97
SQL
ABORT 300
ALL 306
ALTER TABLE 304
ANALYZE 314
AUT01NCREMENT 299
AVG() 306
BEGIN 315,317
299, 300
COLLATE 298
COMMJT316
COUNT()306
CREA INDEX 313
CREA ABLE 295
CROSS JOJN 308
DEFAULT 298
DELETE FROM 303
DISTJNCT 306
DROP INDEX 314
DROP ABLE 296, 317
END 316
ESCAPE 311
EXPLAIN 313
FAIL 301
FROM 308
GROUPBY 306
V1NG 306, 309
IGNORE 301
1NNER J01N 308
INSERT 315
INSERT JNTO 301
JOJN 308, 309
LEFT JOIN 309
LIKE 310
LIM1T307

()306

MIN() 306
ON CONFLICT 300
ORDER 307
PRAGMA 295
PRIMARY 299,300,313
REINDEX 314

203

205

201

199

203
200

209
197

201

for 61
whi1e66

66, 67

69

71,73

69

67

69

73

69

70
71, 73

69

69

69
69, 70

73
math 72
random 73
71,73
70
73
73
70

73

RELEASE 317
REPLACE 301,303
ROLLBACK 300, 316
SA VEPOINT 317
SELECT 305, 308, 314
SUM() 307
UNIQUE 299, 300
UPDATE 303
USING 308
VACUUM 304,314
WHERE 305, 308, 309
306
314

703

301
305

312
303
293
295

315

303
317

317

304

308

~ .

Python.

www.bhv.ru

" "
., ., . 29, . : (812) 251-41-10

www. techkniga.com

E-mail: opt@bhv.spb.su


- n

SQLite
n SQLite
MySQL
n PIL

n

n
,

Python: n , n , ,

, ttu, -

nr,

SQLite, n n SQLite MySQL.


n PIL n
. n n , n
n

Python

n, n , n n
~s n.

http://wwwadmin.ru/ n n
, n, no
Python.

ISBN 978-5-9775-0797-4
-16

180005, c-J-Ilmlp6ypr,
3aiJ8eloij np., 29

9 785977 507974

E-mal: mal<illllv.ru
lntlt'118t www.ldiV.ru
.: (812) 251-42-44
allc: (812) 320-01 -79

También podría gustarte