Documentos de Académico
Documentos de Profesional
Documentos de Cultura
PyQt
2012
681.3.06
32.973.26-018.2
84
. .
84
-,
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
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
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
................................................................................................................................... 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
..............................................................................
123
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.
.............................................. 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
12.
....................................................................................... 216
14.
............................................................................ 247
17 .1.
17.2.
17.3.
17.
................................................................................... 319
n n ........................................................................................................... 319
n ........................................................................................... 324
18.
............................................................... 340
19.1.
19.2.
19.3.
19.4.
19.5.
19.
20.1.
20.2.
20.3.
20.4.
20.5.
20.
............................................................. 398
........................................................................................... 398
............................................................................ 40 1
...................................................................................... .403
....................................................................................... .406
20.5.1.
20.5.2.
20.5.3.
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
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
10
25.1.
25.
..................................................................................... 551
................................................................................................... 551
26.
.................................................................................... 578
11
27.1.
27.2.
27.3.
27.
....................................................................................... 607
.................................................................................. 607
28.1.
28.2.
28.
SDI-
n ................................................................................ 640
.................................................................................................................................... 644
12
28.2.3.
28.2.4.
28.2.5.
28.3.
28.4.
28.5.
28.6.
28.7.
.................................................................................................. 648
............................
v 665
. ................................................ 666
- 667
Python-
Python
PyQt!
, .
, , ,
W-, .
Python
, ,
.
Python 3.2
Windows.
"". ,
"". , .
Python
Python
( n)
pyw (
).
.
-
. , ,
-. ,
, , ,
.
Python
- . ,
, .
, . , ,
, .
Python
, , .
, -, ,
.
Python
-, .
'Python-
. ,
Perl
. ,
Perl,
14
.
Python
, . .
. ,
llttp://pytln.org/dcv/peps/pep-0008/.
.
Python
. , I
.
.
. . ,
- . .
J< .
.
Python
, ,
. , Pytho
.
r Python ,
Notepad++.
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.
Next.
(.
1.3)
Next.
pyw
5.
Next.
, .
Finish
1.4.
pythow.exe .
pyw.
/. Python 3
18
~ Vy1110t\ 3. 2 S~tup
---
_ta
1j
python
(\)(
1-wiodows
_" __0000"
1
Next >
i'ld,
'"
-0 ""
. .-
. . .. -0000000
..
. ..
..
000
. .
---0
1.1. Python.
"-
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
jg/Pyth< 3.2Sttllp
Ej
------..-----_____..........---......---.= .
- .:" "[.el
13 ReQister Extensions
9 Tcl/11<
;; Doci.'Ielltation
9 utility ScriPtS
::::
Test stite
python
windows
1~ \J;$aQe J
f Advared }
.
1.3. Python.
python
((wr
windows
1.4.
Python.
lt
h stfeatures
20
1.5.
/.
Python
,
,
IDLE,
IDLE
Pyt.hon
in32
~ . 2
(r32:88445,
"copyright.",
f~b
20 2011, 21 : 29 : 02)
"cr~d1t."
or
"l1cene()"
:tor
mor~
1n:tormat.ton.
>;>> 1
Python
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
1 Disk~ 1
Reset
Custom St=tuP
Activestate
~ lcons in tho tree elow to thonoe the "'" features wil onstoled.
lwdd-ive.
ActivePython
1.8.
PythonWin
1<11
. n, n
,
IDLE31.bat. :
@echo off
start C:\Python31\pythonw.exe
C:\Pythonl\Lib\idlelib\idle.pyw
n
n
IDLE.
IDLE.
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
--
~~~::::
)8
/ ") 11
~ fl
lq /i]
1_
Pro --..".-----, - -------.
! ~~ --~--~-.. ~1 ..
!l64 8 ...
1. - 11 >\8 "test.r"
8 <I1111 ~ no e-rnad. ..
python
,;>
---- -------
_j
0f~<3!1
EJ .
pythonI
1 .",. python2S
i : ; nr;
t~
~ ..
~--------'
jj -- -~---------- ---...-------
8!:!d
r111011
epet1eti()83Tb
<
1.9.
n nr
Python
n test.py n ,
n . n
: ...................., ...................... , .....................,~~...........~. ................. .. . .....,, ., ..... ,..............................! ...............
~ 1.1. ~!f
1.1.
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,
Python 3.2.
1.2.
Python
,
", !". n1-t ,
Python ( 1.2).
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.
.."
>>> # n n
>>> rint (", !"}
, !
>>>
.............................; ...................................... ;
print()
>>> , .
# -*- coding :
<>
# - *- coding:
IDLE
1251
-*-
Windows- 1251 :
-*-
.
.
, ~
.
/. Python 3
24
n n n , n
Windows.
, n . . n
,
input (),
<Enter> n .
, n 1.4.
t''''''"'''''''''"'"''''''''''""'' ' "!''''"'''''''""''''"''"''"'"' ' ''.,.'''""'"""''"'''" ' " " "''' ' "''"'""'''"''''"'''"-.''"''''''"'"'" "' "''''" '''' "'"''"''''"' '' '"''"''''""'""'.,.,,,,.,,,.,,,,.,,,,.,,:..oo"'''' ""'''"'t
#
#
.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
1.3.
, n Python n
. n .
, , -
( 1.5).
r.
. . . . . . . . . . . . . . . . . . . . . . . . . . .. .,. . . . . . . . . . . . . . . . .. ,. . . . . . . . . . . . . . . . . . . . . . . ...,. . . . . . . . . . . . . . !
~,,,,, ,,,., ,;..,. ,,, ,..,,,..,,... , , ..,>oo;,,,.,..,,,,.,,,,,;, ..,,,,,,.>.. ,,,,,;,,.. , .,.. ,,,.., , ,.,, ,, , ,,,.,, , .,.. , ........... , /ooo oOoo.,OoOo ooOo o. ooo"'''''''"'l''.,"''...."iOo oooO> . .... ,,.... , ...;,_,~00"'''\,A, , .. , , ,,, ..,, ..ooO..oooooOoooooOo oO'"'''"' ' ' ' ' ' " j
>>>
import sys
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.
IDLE
n n
n . n n n
n n , n
1.6.
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).
=1
while i <1 1:
print (i)
i += 1
p rint ( "
n")
n. i
Python i . , n
, .
. ,
.
. Python I
I .
Python n n n
, . ,
1.
27
, n
n n:
\.
. ( ) n. :
=
15 + 20 \
+ 30
()
n . n, . .
. :
(15 + 20
+ 30)
()
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 ()
n ~, n:
rint(", !")
n n,
print("#
")
Python
( n):
28
print (",
!")
/. Python 3
, , . .
.
. , . .
.
, .
1.5. IDLE
JDLE.
.
,
Python Shell
> r .
<Enter>.
( , ), -
.
<Enter>
.
,
<Enter>.
>>>
", !"
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 ().
[,
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
print("Cpoa
print ()
. :
1 2 3 4
for,
print (), .
, . Pytln
. ,
, . .
. ,
.
.
print () ,
1.
31
,
. -
'. . :
print ( """ 1
2
3""")
~J :
1
2
3
print ()
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 "
", ~
<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
.
n eval () n
"))
#:
2 + 2
4
eval ()
. ,
n . n
n argv sys. n argv
, n
test.py
C:\book.
n .
1.1 .
n . > : n n.
crnd
n . ,
1.
n . n
33
C:\book.
od
:\k
:
:\k>
n n :
(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).
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)
:
1349
34
/.
Python 3
help () n
, . n n
. n, n builtins, n
, :
_doc_.
help () n n .
.
n n.
test.py:
def func():
"""
pass
"""
"""
n n :
test.py
n:
test -
FUNCTIONS
func ()
n
FILE
c:\book\test.py
n n n
test.py
_doc_:
1.
35
n:
n
doc
n:
dir ():
test.
:
[
1
builtins
_package_ 1 ,
- cachedfunc 1 ]
doc
file
name
n n :
dir ( J .
'
test .
:
[
builtins
doc
name
__package_ 1 ,
test 1 ]
Python n . n
. n . 1:1
( n ) .
.
2.1.
, ,
, n . ,
' , . .
. , ,
n , n n
,
.
n n .
,
;"'" .........._ ..........,...
~-~
2.1.
r 2.1. n Cf!OB
.
, ,
(
~.. , . ...,,....... "t .... , ........~ ................... ,....................~~
2.2).
...........
\
''1...~''"'"'"""'"'''''''' '' ' '.'' '"'''''''''' ' '''"'"~\~ " . .. ..~'"''''"'''"' '''''''"'''""''"''''"'"' '" '.'''"'"'..~.. ..
> help(abs)
Help on built-in function abs in module builtins:
2.
37
... )
s(
as(numer)
->
numer
> help
> help
10
10
help
help <)
1.
help ,
. .
. ,
.
, ,
str.
str
n
n .
IDLE
. ,
. , ,
. -
, 2.3.
:..,.............. ,....,..., .. " ..........,..,,,,..,,.,.1 ..'''' '' '' '''"~'',1,"1"t.."""''"'Y"'.~''>'-'"'"'''
... , ....~ .....,..,,,,,,~,,..........., ..~..,,,,".,,,., ,".,,,., ..._,,,,,,.,. .... , ... ........, . ,., "'!-'''" '" ~' ' "'''f'"'' ..''"''""''!
'''''"'"'"!"''.,._,, ~
:.,,.,_"...,.,,,, ,,,,,,..,., _,,,,,,"''''''''..,,...., , - , ,..,.,,,,,,,,",,,... , ,~,",,,"{,,,,.,,,,,j,).,dooo..o"...Oo",o,;,,,,., , ,,,,w,., ..,.,,,,.,,,..,,...,ioo"ooiAO..ooooOoooOO" , .o,",.",~.,\. , ,.,"., , oo.,,,,,,.,, .... ,, ,,,,, ,, , , ,~,,ll< ... "~"<<lo"'"'"";
n :
ly,
. . .
, . . .
~ , :
>
>>>
10
= 10
11
!( !
!!
: -
:
>
>
= 10;
(10, 20)
= 20
38
2.2.
Python 3
Python 3
/.
n :
NoneType- None ( ):
> type (None)
<class 'NoneType'>
None n False:
> bool(None)
False
int-
. n n:
float-
cornplex-
n :
s t r - Unicode-cpo:
>>> type ("")
<class 'str'>
n :
bytes -
bytearray-
n :
list-
n.
tuple-
list
n-
39
2.
+ dict- . dict
:
"":
20} )
+ set- ( ):
>>> type ( {"",
<c1ass 'set'>
"",
""}
+ frozenset- :
>>> type (frozenset (["",
<c1ass 'frozenset'>
"",
""]))
()
>[
'
+.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'>
.
,
2, 3]
bytearray.
#
n n
40
, , n
bytes. ,
/.
Python 3
, ,
n:
>>> str1
>>> str2
>>> str
>
""
""
str1 + str2
print(str)
, .
, , , n bytes bytearray,
-.
, :
next
()
next ( )
2
, :
>>> d = {"": 1,
>>> i = iter(d)
>>> i. next ()
":
2}
''
>>> d[i.
1
next
()]
. .
for,
II . n, n
:
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 :
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)
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("")
( -
~),
10).
int("A", 16)
, :
. :
2.
+ str ( [<> J ) -
45
. :
'2')
bytes (<>,
<> [,
< !1>] ) -
bytes. !l
),
"replace"
"ignore".
"strict"
bytes (<>) - .
255 bytes. ,
Va1ueError. :
>>>
>>>
'\1\2\0\\\0'
>>> str (,
"866")
''
bytearray.
),
"replace"
"ignore".
"strict"
46
1.
Python 3
trr(<> J - n
255
>>>
bytearray.
Va1ueError. :
nn ,
>
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.
-" - ""
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:
~ 2.5. ~>,
: .....~ -- - - - ..... ............. ...~..... ....... .... ,. _ , , .._,.,.,., ,, .,_, , .,., .,.-,.,, ,~..........-........~......................-.),,," .... ,.,.,.. ,......,...-.~.....,_,_..,..,.. "''''-'""""''"''..............................,..,.. ,_",.,.,..,.,,,,,;
= 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):
n, n- n .
, n ,
n , n n
. n .
n n
. n, n n
:
. , , n , n
. n n ,
n
decima1:
Decima1 ( '0.0')
3.2.
n n n . Pytln
n n n:
-- . nn:
>>>
100
>>>
# 01100100
# 10011011
& - :
>>>
>>>
>>> z =
>>>
100
75
"{:)
&
&
(1:)
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:
+-
"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.
5.
& - .
- .
7. 1 -
n.
n n n
n , , n .
> True
1 :
1 + 2
> False + 2
+ 2
2
n:
>>> = True;
))) ,
(True, False)
False
n (rue) 1.
(False). n ~ bool 1).
True :
, :
n :
, :
n :
False:
56
/.
Python 3
None:
> boo1(None)
Fa1se
4.1.
. :
==-:
>>> 1 == 1, 1
(True, Fa1se)
!= -
>>> 1 != 5, 1 != 1
(True, Fa1se)
<-:
>-:
<=-
>=- :
in :
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,
(True, Fa1se)
is, not
:
>
>
= [1, 2]
is , is not
(True, Fa1se)
>
>>> 1 <
10
< 20
>!'
:
==
True
True
Fa1se
Fa1se
/.
58
Python 3
or- or - . n Fa1se, ,
n - :
True
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 ).
% 2 == 0:
print (, "else:
prin.t (, "input ()
") )
if
")
")
, !'
:
* -*
2 =
else: print
input ()
if
:
(,
print (, ""-
") )
")
")
. ,
, :
")
")
input ()
, , , . .
n
. ,
. , ,
:
if
") )
%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
-'""')
elif
. ,
:
elif os
= "":
False,
True
. n
not.
n . n
( 4.3).
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
< >
% 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
, n n .
Python
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 ,
~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.,"""'""'~'""'''" "'' '''""''"""'"""""" .. ""'''''"'..,.
z 3
keys( )
4.
63
z3
, n n,
, . .
n, n
sorted ():
1
2
z3
n for n . 1
n (
........................................................................
4.7).
~"''"'"'''''"''''''''''''''''
~ 4.7. n n
..".
......... ..............................................................................................,
''''''"'""''''''
lo_,,_.,,...,,..,,,,,,...,,,o~n,.,,"_,,,,,,,",,.,,,,.,..".,.,,,,,.,.,.,,,,.,,,.,",.,, ..,,,..,,,.,,.,,.;.",,,,,,,,.,,,,.,,,,,,,..,.,;,,.,,,.,,,,,.,,_.,",,,,,_,,.,...,.,,,...,.,,,.,,,,,,,,,,..,,,,,,,,,,,.,,,.,,,,,,,,,.,,,,,,,,,.,,,.,.,,.,,.,.,,,,,,,,.,,,,,,,,w,,,,.,,,,,,:
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 ()
<>
1)
. n <> ,
no
n . .
, . n
64
/.
Python 3
<> , 1. ,
. for
.
2 (
4.8).
!"t""".,..., , ......., ..., .._.,,._.,,'l!.,.,_,.,",
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(100,
100 1:
-1): print(i)
~ .
100:
. ,
. ,
,
:'"\"~''' '''''''''' "''"''''' ' '''''"'""' '' I''~" ' ''""'"'''''''"I''"''''''''" '"-''1!"'""'~'\"'~'\\ ~-..."A~~~r.,..,-,:;?f''''''""'P"''"~'~"'"'.(-~ 'v..",o_.,,,,...,,,.w~v~t""'''''''..,'''''"~'''''"""'""'''''""'' '''''"':1
r-4.9.
range
n n
4.
65
+ index (<>)
n :
- , .
Va1ueError. :
>>> obj.index(5)
+ 1t (<>)
, . :
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:
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. .
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 .
. . .. . . . . .
. . . . .
..
. .
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).
~ 4.14. n oontinue
t .........;.u......... ~.............o........................................................~.........l o,,.. ,"''"'''''''"""''"'~.t ... , .......1..; ..~........ ~..... ;,, ...... ;,,.., ............ ~~..~....................; .., ....................................................;
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
;,,_,,.................-......................................................
.......- ................
......................................................- ....,; .............................................................._,........- ........... .......
~
~-+
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:
9 F ( ):
( ):
1120,
1.1+21,
2.5-12
2.5-12)
/. Python 3
70
. ,
:
. , , , 1
. ,
decimal:
fractions:
>+<
>J
> 2+5J, 8j
( ( 2+5j)' 8j)
decimal frp.ctions,
. .
5.1.
( 10). :
>>>
(7,
>
(0,
5.
71
> float ()
0.0
+ in (<>)
. :
oct (<>) -
'',
'-01101')
. :
+ hex (<>)
. :
+ 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)
.
, :
+ abs (<>)
- :
+ pow (<> 1
>>> pow(10, 2) 1 10
(1001 100, 271 27)
<> <>:
** 2 1 pow(3 1 3) 1 3 ** 3
, :
+ max (<
(10
** 2)
% 2, pow(3 1 3, 2) 1 (3
>) -
** 3)
%2
72
/.
Python 3
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
* 2.0 + 1.5
5.2.
math.
math ,
. ,
:
import math
n n
cmath.
math :
pi -
n:
>>> math.e
2.718281828459045
:
~ (, ,
). ;
5.
75
+ 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,
( 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,.,.,~";..,,,,,,,.,,.;,,,;,,,..,",,,.,,.. .,\,...,.,,,.,,,,.,,,.:
1n 1,
''
, ,,, ' 1
1 ,
', ''
',
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 ).
no
''
Python 3 :
str - Unicode-cpoa. ,
(UTF~8. UTF-16 UTF-32) . ,
, Unicode
n . Unicode-cpoy
- :
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
, ,
.
, . :
bytes , .
, ,
1en (1 ,
"1251"))
>>>
12
len(bytes("cpoa",
+ bytearraybytes,
"utf-8"))
bytearray
n ,
. :
, ,
"".
str.
bytes bytearray
, , ,
.
bytes
bytearray
6.1.
.+ str ( [<> [,
,
. , .
78
/.
Python 3
'[1, 2]',
'(3, 4)',
str((,
"{'':
>>> 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
):
'2')
>>>
'',
('',
>>>
"",
'',
'"":
'"":
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
, , , ,
:
>>> "string
SyntaxError: EOL while scanning string literal
n ,
\,
> "stringl \
string2"
'stringlstring2'
> ("stringl"
"string2")
'stringlstring2'
>>> ("stringl" +
"string2")
'stringlstring2'
, \, ,
:
>>> print("string\")
n .
.
. :
>>> print(''
''')
'l
2
l
2
>>>
print("""Cpoal
2"
"")
l
2
nn , .
_ doc_
, .
,
:
/.
Python 3
"""
pass
>>> print(test.
doc
n, (
n) n
n .
r,
. , \n .
, : \
>>>
n:
print("Cpoal\nCpoa2")
>>>
print(r"Cpoal\nCpoa2")
l\n2
(r"""l \n2'""')
l\n2
, :
>>> print(r"C:\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\\
, ,
:
81
6.2.
- ,
, .
, ,
\n-
\r-
r:
\ t - ;
\ v-
\- ;
\- ;
\ f - ;
\- ( );
\"-;
\' -
\N- N. , \74
\xN- N. , \ j;
\\- ;
<;
,
, :
("
\ n")
\ n
, :
(" \\ ")
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'
# , <>
>>> 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 ():
for:
> s = "Python"
> for i in range(len(s)): print(s[i], end=" ")
:
Python
, 1 n
:
>>> s = "Python"
Python
n n+:
"2")
12
, n '[ .
"2")
12
, , 1
, :
>>> s = "1",
>>> type(s)
<c1ass 'tuple'>
"2"
, , . ,
, :
>>> s =
"1"
> print (s +
"2")
12
84
/.
Python 3
n (n, )
n n n n str ():
'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 <>
, . :
'Nik- 1978'
85
+ <>- . :
#-
(
) ( ),
, <>:
>>> print("%#o
77
12
%# %# ..
(77,
12
- :
--
(3, 3) # 5 -
. ,
. :
11
'3
n- .
. :
3'"
+- , ,
. + n, n
. :
'+3'"
+ <>-
, :
'3
86
/.
Python 3
<>- .
. :
"*"
< >- . .
< > :
s - str ():
>>> print ("%s" %
(" "))
[1, 2, 3]))
r - repr ():
>>> print ( "%r" %
'
10.5~,
("
"))
'
ascii ():
- .
:
=>%"%
(i, i))
d i - :
- :
12
12
- :
87
+ , - :
> print("%X % %" % (Oxff, 10, 10.5))
FF
> print("%1!X %# %" % (Oxff, 10 , 10.5))
OXFF
f
F -
n:
+ - n ( "" ):
> print ( " %
% "
3.000000+3 1.865781+4
+ - n ( "" ):
> print("%E
3.000000+03
%"
% (3000, 18657.81452))
1.865781+04
+ g - f
( n ):
+ G-
1.865-005) )
f ( n 11):
1.865- 005 ) )
n n,
. & :
n n n L
. n '!r~ n %,
- . n (11r
6.2).
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:
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 (<>) -
. .
,
. :
90
6.5.
format ().
/.
Python
format()
Python 2.6.
\I ,
<>= <
**kwargs)
n opaa>.format(*args,
< n >
{ }
, :
{[<>] [!<>] [:<>]}
, , .
ValueError.
{}".
format
1 },
("n",)
<> ( )
. .
.
format ()
. :
format ()
{O.color}".format(car)
, <> .
, :
91
{ 1}
{2}
{n}"
'1-2-3-4'
{}".fonat(1,
'1-2-4-3'
<> , n n
. "s", str (),
# str ()
# 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
, <>.
, :
<>. :
+- , \.
;
+
+
-- ( );
- ~ .
. :
'-3' '3'
'-3'"
3'
'-3'
11
<> :
- :
- :
>>> "'{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, :
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)
n <>
:
+f
F - n:
'18. 657815'
n n n n <>:
'-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.0087%'"
94
/.
Python 3
6.6.
:
str ( [<> J) -
". n ,
. print ()
[1, 2]',
"{'':
'(3, 4)',
1}")
repr (<>) - . n
Python Shell
IDLE.
ascii (<>) - n .
ASCII.
>>>
"{'
5}")
ascii("cpoa")
"~\\u0441\\u0442\\u0440\\u043e\\u043a\\u0430'"
1en (<>) -
strip ( [<> J) -
. : , n
(\r),
(\t)
(\n),
(\v) :
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, .
, .
, ,
. :
'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 :
+ r5lit([<>[,
<>]])- , 5plit(),
- , , , .
:
+ 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
- n -
. ,
n n , - -,
- , n n -. n
n. - , n
, n. :
n n, , , n .
, n n,
. :
join () -
n n .
. :
<>
<>.jin(<>)
n n n :
TypeError:
join ()
>>> s = "Python"
>>> arr = list(s); arr
['',
'',
't',
'h',
'',
list (), n
n n . :
'n']
97
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,
6.3 ).
. .
;..;..":"'"""'""'"""''''""'""'""' ............ : ............ :............ ; ......................... :ii ..............:.................~.i~ ................................................................................ ' ............................................. .
> #
> 1oca1e.set1oca1e(locale.LC_ALL, "")
'Russian Russia .1251'
>>> #
> 11. get locale ()
('Russn_Russia',
'1251')
4 . 1349
98
/.
Python 3
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 () - ,
-:
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. :
7)
index () -
find (),
ValueError. :
<>.ind(<>[,
<>[,
<>]])
rfind () -
s.index("p",
1)
. , ~ -1.
. :
<>.rfind(<>[,
<>[,
<>]])
, .
<>
<> ,
. :
100
(7, 21, -1)
>>> s.find("p",
(0, 14)
rindex () -
6),
s.find("p",
/.
Python 3
10, 20)
rfind (),
n ,
Va1ueError. :
<>.rind(<>[,
<>[,
<>]])
count () -
6)
. n
, . .
:
>>>
>>>
(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 ,
. :
2.5;
<> i :
endswith () -
, n.
,
.
True, n - Fa1se.
101
:
<>.nd5with(<>[,
<>[,
<>]])
, .
<> <> , ,
. :
2.5,
<> :
rep1ace () -
.
. :
<>.r1(<
D,
< >[,
<
>])
>>>
print(5.rep1ace("ne",
""))
""))
>>> 5 = "5tr5tr5tr5tr5tr"
>>> 5.rep1ace("5tr", ""), 5.rep1ace("5tr",
1 1
1
,
(
5tr5tr 1 )
3)
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})
''
, .
<> ,
, <>. :
None. translate ()
. , :
6.11.
isdigit () - rue, ,
False:
isdecimal () -
True, ,
False. ,
ASCII,
. :
>>> "123".isdecimal(),
(True, False)
isnumeric () -
"123cp".isdecimal()
True, ,
False. ,
ASCII,
. :
isalpha () -
103
rue, ,
- False. , False. :
isspace () - rue, ,
- False:
isalnum () - True, () ,
' - False. , False. :
"ac123".isalnum()
>>>
"cpoa".isalnum()
True
"
.isalnum(),
",
123.". isalnum()
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. ,
. :
istitle () -
rue, ,
, - False.
, . :
"
123".istitle()
" cp".istitle()
104
/.
Python 3
4.16)
, n, , n ~1
n ( 6.4). . n
.
~'"'"'''""'""''""'''"""''"'''"'''''~--"''""'"""'"''"''''''''''''''"''''"''''''"""''''''''''"'"'"''"''"''"'"''''"'''''''''''"'''''''''''"'''"'''''''''''''''"''''''"'''"'"'''''
l .4._.t.il.t()!;!~~Qn~kJ"1~&
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 ()
''
"strict"
(n
UnicodeEncodeError;aee
),
n)
( ).
no
"ignore"
"replace"
encode([encoding="utf-8"] [, errors="strict"]).
, n n
"".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�'
>>> "cpoa\uFFFD" .. encode (encoding="cp1251",
errors="backs1ashrep1ace")
b'\xfl\xf2\xf0\xee\xea\xe0\\ufffd'
( ) , ,
. ,
,
ASCI\.
bytes (<>),
255 bytes.
Va1ueError. :
>>>
>>>
'\1\2\0\\\0'
>>> str (,
"866")
''
bytes (<>),
. . :
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
, ,
. ,
. ,
:
bytes
. ,
, :
bytes , -
, ,
3.2.0,
. ,
bytes, :
bytes
. ,
:
bytes , .
.
, ,
1en () , :
108
>>>
6
>>>
6
>>>
12
/.
Python 3
ln("")
len(bytes("cpoa",
"1251"))
len(bytes("cpoa",
"utf-8"))
'')
n n str () :
"1251")
''
, n n bytes ,
n n, .
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 (<>), n n
255 n bytearray. nn
Va1ueError. :
n,
bytearray (<>), n
. :
> bytearray(5)
bytearray(b'\x00\x00\x00\x00\x00')
bytearray. fromhex
(<>).
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 (<>) - .
. :
extend( <>) -
. . :
, :
insert (<>,
n:
<>) - .
. .
1 :
111
insert () .
, .
:
( [<> J ) -
, ,
. , .
:
115
>>>
bytearray(b'trin')
t remove (<>) -
del:
, .
ValueError.
. :
t reverse () -
~ . :
bytearray
decode ().
"strict"
( ),
n:
'')
"replace"
"ignore".
112
/.
Python 3
_ str () :
>>> = bytearray("cpoa",
>>> str(b, "1251")
"1251")
''
6.14.
pick1e. ',
:
import pick1e
:
dnps (<>[,
<>][,
fix_imports=True])-
.
(
3).
1oads (<
>[,
fix _imports=True] [,
encoding="ASCII"] [,
errors="strict"])- n
. :
6.15.
hashlib. n
, :
import hash1ib
:
update ().
113
>>> h = hashlib.shal()
> h.update(b"password")
di gest ()
hexdigest ( ) :
>>> h.hexdigest()
'5baa6le4c9b93f3f0682250b6cf833lb7ee68fd8'
mctS (),
MD5.
, . .
.
, (
6.6).
................................................................................................................................................................................ .. . . _
........~................. .....................~
r ~.6. n napon
t ~ ~ -
....................~-
................... . ...................................-
,
...................................................... .............. ,
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.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 "" )
"")
ASCII- \w,
\w;
\, \, \d, \D, \s \S
, ~etrf , ,
r. , n .
, . n,
:
= . re.compile ("\\w+$")
~t
.,
,$,*,+,?,
{, [, ), \, 1,
( )
. ,
. n~ ,
. . ,
"" ~ , n
. ~ ,
( 1 . 1). n n
n (
7.1 ).
..
;t~~~~'!I..'""''"~"'~t'"""'''""t.'~t.,'~'"'''"'''''"'"'',.."'''H* , "'''''''''''''''"~'''"~"' " ''"'''''''~"'''"' '''''''''''''''''' ' ''' ' ''' ''''''''"''"'"'''C'"''""""'''-''"'"'"'''''''H'"'''''''''''""''' ' '".'"'''-~- "'1
..
:,...,,._.,,",.,,,,,,,.,,,,\,,.,,,,,.,,.,,......~ .......,,.,.,,.,,,",,.,,,,,,,,,,,.,,,lo; .. .,,,,,,,,,,,,.,,,_,",,,,,,,.,.,,.,.,,,.,",._..........\l'h'ii..oo.,~. ............o...................... o1'; .:.......,.,;.,, ....... t .-....., ......: ....................,.,:,,u,,;,,,,,,,,,.,,,.,;
"29,12. 2009"
re.compile(r"[0-3)
"\"
116
if p.search(d):
print ("
else:
")
print("aa
")
~:
'
/.
Python 3
"\",
= 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
.................. ............. ::... .............................::......... ,:.......... .....-::: ....:;.... ;.;,;;,;;:.........:;;::.....
;
~;;;;~:
,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 "" (
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
"";,,,,,.,. .,;,,,""',..............
"""'
................................
'
if
re.compile(r"[0-9]+$", re.S)
p.search("Cpoa245"):
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-] - ;
[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];
(ASCII)
7.
119
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 . .
{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
?P<name>. n
7.1 0) .
...... ,.......................................; .......... ;;,,,;;;~ ................ ;,,,;,;,,,;;;~ ... ;.;,,,,,;,, .. ,,,,;,,;;.... ; .....;,;,:,,,;,;; ..........................,;;,,;.;................:.,;;.. :..:................................
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:
+
+
"" ,
compile ();
(?# . ) -. ;
(?= ...
)-n n n. , n n
n:
(?! ... ) -
re.I)
u n n. , n
n:
re.I)
(?<= ... ) -n n . , n n
n n:
122
/.
Python 3
+ (?<! ... ) -
. . ,
, :
(? ( id
name) l11j!2) -
. ,
l,
2. ,
. , :
, ( 1\5)
(\51$) .
, ? : :
"word2"
"word4"
? ' .
, .
, . . , .
, :
"-wordl
<>-wrd2
-word
-word4 -word5"
"-word2" ,
. "word",
:
"-wordl -word2
-word
<>-wrd4
-word5"
"-word4" , .
"word2"
"word4"
"word5",
, . .
naf}a
7.
123
. ,
(?= ... ) :
(?:\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"
"")
print("Haeo"
"")
= 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
1.
Python 3
"")
>>>
print("Haeo"
if p.search("l23str", 3) else
"")
r.srh(<>,
<>[,
<>])
n <>
. <> ,
n
compile (). ,
None. :
Match,
>>>
>>>
= r"[0-9]+"
"")
= re.compile(r"[0-9]+")
if re.search(p, "strl23") else
"")
print("Haeo"
>
>>>
print("Haeo"
n (.
4.16)
, , , n
(
7.12).
, n .
Match,
()
match ()
1.7)
search (),
r e - n ,
search (). :
n ;
groups-
groupindex-
()
match ()
+
+
+
+
+
7.
string-
125
<> ()
match ()
search ();
- < 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
nameN> JJ) -
. ,
, . .
, , .
. ,
, .
,
IndexError.
groupdict ( [<
> J )
. ,
None,
, :
126
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',
')
, ,
- . ,
-1;
, ,
- . ,
-1;
. . ,
, - .
, (-1, -:1). :
>>>
>>> s = "str123456str"
>>> m = p.search(s)
>>> m.start(), m.end(), m.span()
(3, 12,
(3, 12))
(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''"''::"'""""'''.'''""'"''''"''''"''"''''''""'''~''''"''"'''''::::.''".'''"'''''':':~:::"'':""'''.:::.~.''''''"''"''~"':'.''"""'::'"''"''''''':'.'''''''.'''''''''''"''''''''.'''''.''''''~'"~''"''''''''''''''''''"'''''''"''
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']
[]
> 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
'2',
>>> = re.copile(r"[0-9]+")
>>> re.finda11 (, "1 2 3 4 5
'2',
['1',
")
'6']
")
'']
finditer(<Cpoa>[,
< >[,
< 3>]])
> =
> for
2007
2008
2009
2010
2011
re.copile(r"[0-9]+")
start: end: 4
start: end: 10
start: 12 end: 1
start: 18 end: 22
start: 24 end: 28
re.finditer(<ao>,
<>[,
<>])
<>
. <> ,
i1
().
re.S)
print(.group(1))
Text1
Text3
7 .4.
sub () .
, . :
< >
\,
\g<>
\g<>, .
:
>>> import re
> = re.copile(r"<(?P<tag1>[a-z]+)><(?P<tag2>[a-z]+)>")
7.
129
>
\g<>
\g<>
n Match, . ,
, .
10:
= re.compi1e(r"[0-9]+")
print(p.su(rep1,
Match """
priht(p.su(rep1,
input ()
:
BHHMAHHEI
.
su () . su (). :
r.su(<>,
< >,
< >[,
< >
[, flags=O]])
<>
n . ,
:
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
< >[,
<>[,
fla9s=O]])
<>
. :
escape (<>)
, .
. :
:- .
. n n
n n n .
. ,
,
1.
n n n .
n, n , n ,
(n+), n (n*), n (n
in).
n n . , n
, :
#
#
n . , n
, :
>>> t
> t
(1, 2, 3)
[0]
#
#
'
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 :
+ 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 :
#
#
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
[ []'
#
#
[]]
[5]]
n n
append 1)
>>> arr
[]
>>> for i in rangel2): arr.appendl[])
>>> arr
[ []'
[]]
[]]
n :
[]]
[]]
, 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 ).
listlx)
~;;;,;:,;;,
= [:]
>>>
8.
[1, 2, 3,
>>>
135
is
4, 5]
False
>>> [1]
100 #
>>> ;.;,
#
( [1, 2, 3, 4, 5]' [1, 100, 3, 4, 5])
, .
is
, .
. ,
Python
>
>
>>>
. :
False
> [1] [1]
>>>
100
#
#
! 1 1
[2, 100, 4, 5] J)
,
.
,
is
1ist {)
, ,
. . ,
1ist ()
,
(
deepcopy ()
8.2).
"!'"''""""'"'.''""'''''""'""""""''"'''""'''""''''""''"'''-'"'"'''"''"''''""'""""'""'''''"'
f..P~~~~~--~:~~.?..~~~-~::~~~~-~~:~,1.q~-~-~~~,~~-,:~.,,,,
>>> import
>
[1,
[2,
3,
4,
[1]
>>>
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]
136
> z[O] [0] = 300
>>> z.
[ [ 300, 2] , [ 300, 2] ]
>>>
#
#
/.
Python 3
[ 1, 2]
8.2.
,
. .
:
, :
>>>
>>>
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[1en(arr)-1]
137
#
5
, , ,
IndexError:
, ,
, :
(5, 5)
,
:
[600, 2, 3, 4, 5]
, ,
. :
[<>:<>:<lli>]
. <> ,
. <> ,
. , , ,
. <> ,
.
. . :
[1, 2, 3, 4, 5]
>>> m is arr
Fa1se
is
~,
-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]
. ,
, , :
[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, ]'
[7, 8, 9]
, :
. ,
. .
:
["",
""],
3],
[4, 5, 6],
[7, 8, 9] ]
[]
''
[""]
"":
10,
"":
["s", 5] } ] ]
[0]
8.4.
for:
>>> arr
[1, 2, 3, 4, 5]
1 2 3 4 5
, i ,
(, ),
:
>>> arr
[1, 2, 3, 4]
()
[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 () :
<>]
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]
. 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 = []
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]
, ,
, .
. :
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).
~. ~.
map ()
n n.
n , n n
.
n (
8.4 ).
"""
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 :
"""
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>]
(2, 5, 8),
(3,
6,
9)]
n , nn
,
,2,
6, 8;]
n n n (
n n
; ,:, ,.;;,:.:,; .~..... : ... ''. : . i ,;,,; .:. ; ' ............................. ' ... ' ...
[1, 2, 3, 4, 5]
arr2
arr3
+ z for
(,
filter
1)
8.5) .
....-.-
.......
.
.
arr1
arr = [ +
print (arr)
8.4)
zip 1) map 11 (
n n n n.
:
filtr(<>,
<>)
n n None,
n n True.
False,
. , n , n
Python 2.
list
None,
n n
1).
Python 3,
[], 2])
[], 2]))
[ 1' 2]
n n n :
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 >=
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"~~~~()
.;:.::.............. ;;..
....,. ....
,,;,,.';;,,,;,;;~
:.;.',;~;;'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, 4]
>>> arr.append([5,
[1, 2, 3, 4,
[1, 2, 3, 4,
]);
]]
[5,
],
[5,
(7, 8)]
. . :
>>>
>>>
>>>
>>>
>>>
[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, ]
, :
[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
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,
remove
de1:
(<>) - , .
va1ueError.
. :
[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
,
, .
, (, ,
).
{ 1, 2, 3}
# n
# n
TypeError. :
8.
8.8.
147
in.
Fa1se.
True,
in
. , ~
index () .
ind(<>[,
index ()
<>[,
<>]])
, .
Va1ueError.
, . :
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)
rnax ()
rnin ()
. :
True,
, rue.
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!. :
[5, 4, 3, 2, 1]
,
reversed (<>). ,
1ist ()
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 (<>) -
(, , ):
8.
149
+ samp1e (<>,
<
>) -
. ,
.
, . :
8.11.
sort (). :
sort([key=None] [, reverse=fa1se])
.
. :
>
>
>>>
[1,
, 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~
;.: ................... :....... :.::'.'.: ... :::............ :.. :.:: ....... :.:..;;::... :.:: ... :, .. ::::::::::.:.':.: .. : ... :;:.: ..
m:
"2"]
1. ,
key (
m:
8.9).
"2"]
lower()
150
/.
Python 3
sort ( J .
,
. sorted ().
:
key=None] [, reverse=False])
srtd(<>[,
, .
sort ().
sorted() 8.10.
8.12.
'2',
'']
, , range ().
, . ,
<>]
. <> ,
. .
, .
<> ,
1.
10:
>>> list(range(11))
[0, 1, 2, 3, 4, 5,
7,
9, 10]
, 1 15:
7,
5, 4, 3, 2, 1]
(
), sarnple (<>,
>)
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(<>)
TypeError:
str ():
str ()
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)))
.
, . ,
. ,
. :
# ,
, . ,
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
> 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)
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)
. 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 :
. n
start,
- n
step.
154
/.
Python 3
[10,
''),
''),
(1,
(2,
''),
""))
''),
(3,
'')]
(4,
cycle (<>) -
""))
'')]
. , n
. . :
>>> n = 1
>>> for i in itertools.cyc1e("a"):
if n > 10: break
print(i, end=" ")
+= 1
repeat
(<>
< >])
[,
, :
8.15.2.
""))
''),
(5,
'')]
n :
cominations
() -
. :
mintins(<>,
< >)
''),
('',
'')]
('',
''),
('',
''),
{'',
''),
('',
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))
[('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
'')]
''),
('',
perrnutations () -
''),
('',
''),
('',
''),
('',
'')]
, .
. ,
. . :
rmuttins(<>[,
< >])
>>>
2))
list(itertools.perrnutations('a',
[('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
'')]
itertools.perrnutations('a')]
['',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
.'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'']
product () -
. :
rdut(<l>[,
... ,
<N>]
[,
repeat=l])
:
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
('',
''),
{'',
'')'
('',
''),
('',
''),
('',
''),
('',
''),
('',
'')]
'',
repeat=l)]
156
>>> ["".join(i) for i
inproduct('a',
'',
'',
'',
'',
'',
:',
'',
'',
'',
'',
'',
'',
'',
8.15.3.
''
Python 3
repeat=2)]
'',
['',
''
/.
> 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, ,
. :
7,
3]))
dropwhi1e ( <u>,
7,
3]))
<>)
( ), , ,
,
():
return
Fa1se. :
> 3
7, 2, 3]))
7, 8]))
[]
>>> 1ist(itertoo1s.dropwhi1e(func,
[1, 2, 4' 5, , 7, 8]
takewhi1e ( <u>,
[1, 2, 4' 5,
<>) -
7, 8]))
( ), ,
, , Fa1se. :
()
: return
> 3
1ist(itertoo1s.takewhi1e(func, [4, 5,
5,
7, 2, 3]))
157
8.
compress () -
. , (
) . ,
. :
mrss(<
>,
<
>)
>>>
1ist(itertoo1s.compress('ae',
['',
>>>
'',
1isL:(itertoo1s.compress('ae',
['',
8.15.4.
[1,
1, 1]))
'']
'']
, , itertoo1s
:
starmap(<yl..I.>,
<>)-
. ,
.
. ,
, . :
zip_1ongest () -
(4, 5),
[ (1, 2, 3),
(6, 7)]))
(4, 5, 6)]))
, .
,
fillva1ue. :
zi_1ngst(<1>[,
... ,
<N>]
[, fi11va1ue=None])
:
(2, 0),
(3, 0)]
[4]))
[4, 5, 6]))
[4]))
[4], fillva1ue=0))
158
accumu1ate
(<>)
/. Python 3
. . :
chain () -
, . . :
hin(<1>[,
... ,
<N>])
>>>
>>>
[1,
>>>
'',
'',
'defg',
'hij'J
(<>)
chain (),
.
. :
>>>
tee
"defg", "hij"]))
'g', 'h', 'i', 'j']
1ist(itertoo1s.chain.from_iterale(["abc",
['',
'',
'',
'd',
'',
(<>
[,
'f',
<>]
)-
. ,
. :
- , 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
{}
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}
#
#
#
>>>
>>>
>>>
>>>
"")
"")
, .
, None. :
>>> 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~~~; ~~~~~~~~~<>
...........................................:,. ............... """;;:................ ;,,,,,,,,,;,,;. ;;,,, ...,;,,;,,,,; .................... :.... ; ............................. ................................................. ...........
,;
;;;,,,
9.2).
k.. :;, .......;...'................-........ ,.,;;, ..-..............:.:: ...;;.:=~;;,,,;:........ ;,, .. ~.;'l~:];';;[.j~jl~::;;~[~;;;,:.;;,;::;, ....'.=.:;....:.~.:: ..=.;;;~=.:;;;:.:~;;;:;=,;.,; .. :; ..~~; ... :;:.: ..:::~ ..'.';~;.::: ....'. ;:;.~ ;..~.;:.~: :. ;;,, ................. ""''""'"''"'''"''
1)
9.3).
ii'~t;~~~~-:;c~;~~~;~~-~~~:~J~~~-~J-~r;
. . . . . . . .". .". . . . . . . . . . . . .
~
:.. '.:: ..... '' ..... ' .. """." ... "... "....:"." .., ......... ;;,; : ;, ;.~ ;.. "...=;; i. =,;. .. "" .. :;.. ;.. "."""' .. ,;;.~ .. :; :..... "'" ...... ". ;, ;~. .;,.;, ................~ ;,; ;;,.: .,',:: ;;, ;,.,;," "' ......... '.... ;.......... ""' .... ;."........... "' ....... "'"".' ........... ;
>>>
>>>
>>>
>>>
9.2.
. , ,
.
1349
162
/.
Python 3
, , ,
KeyError:
2 }
#
11 last) :
line l, in <module>
#
in. ,
True, - Fa.,J..se. :
>>> d = { "": 1,
>>> "" in d
True
>>> "" in d
False
"":
. ,
, . ,
None , n. :
<
>]). , ,
. , , ,
n. ,
None. :
>>> d = { "": 1, "": 2 }
>>> d.setdefault("a"), d.setdefault("c"), d.setdefault("d", 0)
(1, None, 0)
>>> d
{ ' ' : 1, '' : None, '' : 2, 'd' : }
,
. ,
:
#
#
'':
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).
'""'"""''(''""".''''"'""''"''''"''"'''""'""""""'""'"""'"''""'""'~'""~'"'""".'""".'.~'""""'"""'""".''"""""."!'<'""('"'~~".'.:'"'''".'('.'!'"".'(~.'!"'"""'"."!"''"''""""'""'''"
.........................~. ......... ,.
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}
keys ():
sorted ( 1
164
d =
{"":
1,
/.
Python 3
2, "z": 3}
"":
9.4.
keys () -
dict_keys, .
, . :
>>> d1.keys ()
d2. keys ()
'd'}
> d1.keys() - d2. keys ()
{ ''}
> d2.keys() - d1. keys ()
{'',
'd'}
> d1.keys() & d2. keys ()
{'',
{''
'',
11
'',
'',
va1ues () -
d2. keys ()
'd' J
dict_va1ues, .
. :
dict va1ues
[1, 2]
items ()
dict_items,
. . :
<>
dict_items
in <>- l .
True, - Fa1se.
9.
165
>>> d = {
>>>
1,
"":
"":
2 }
""
in d
""
in d
True
>>>
Fa1se
t get (<> [,
< >]) - ,
, . ,
None
, . :
t setdefau1 t
(<>
[,
< >]
}-
, . ,
, .
,
None.
(<>
[,
<
>])
. ,
. ,
KeyError.
>>> 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
>)
,
. :
1,
'':
3,
'':
2,
'd': 4}
() - :
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 .
, , :
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:
1 2 3
n len ():
1 union () - :
>>> 5 = {1, 2, 3}
> 5.union(5et([4, 5, 6])), 51 5et([4, 5, 6])
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}
- :
-= . 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)
( { 3, 4}'
>>> s
(set (),
>>> s
( {1, 2,
{ 3, 4})
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)
= = - :
170
Python 3
set ( [ 1 , 2 , 3, 4 J )
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 () -
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)
, , - ,
. :
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.
+
+
+
+
+
+
+
+
+
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.
"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
. . :
<~<:
>]
)-
, .
,
struct_time.
va1ueError.
, "% % %d %: %: %S %". :
176
/.
Python 3
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'
asctirne (), n
n struct_tirne, , n n
. :
+
+
+
+
+
+
+
+
%- ( "00" "99");
%- (n, "2011 ");
+
+
%- (n, ""
n);
+
+
+
+
+
+
+
%- (n, "");
%- 24-~ ( "00" "23");
+
+
10.
177
%- ;
%- . :
%%-"%".
strft ime () (
10.2).
24 2011 17:15:00
24.08.2011
10.3.
""
s1eep ()
time
. :
s1(<
>)
.
,
#
#
"m"
time
#
#
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 , ,
, , . :
+
+
+
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 -
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. :
<>-
<> -
12
datetime.AXYEAR
n,
Va1ueError. :
n n :
today () -
>>> datetime.date.today() #
datetime.date(2011, 8, 24)
1.
181
fromtimestamp(<Koeco >)- ,
, n n:
, n 1 . n 1
>>> datetime.date.max.toordina1()
3652059
>>> datetime.date.fromordina1(3652059)
datetime.date(9999, 12, 31)
>>> datetime.date.fromordina1(1)
datetime.date(1, 1, 1)
n :
+
+
+
>>> d = datetime.date.today() #
> d.year, d.month, d.day
(2011, 8, 24)
n
date
(24-08-2011)
n n:
n n .
182 .
n
date
/.
Python 3
n :
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)
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 .
t
t
t
t
t
hour- ( 23);
minute-
59);
second- ( 59);
microsecond- 1 ( 999999);
tzinfo- ( tzinfo None).
Va1ueError.
...
in 0 .. 23
t
t
t
t
t
h- (
23);
minute- ( 59);
second- ( ' 59);
microsecond-
999999);
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
. :
>>> 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:
strftime ()
time.
time
10.4.4.
tzname ().
tzinfo
datetime.
datetime
datetime datetime
. :
datetime(<o>,
<>,
<>[,
[, microsecond] [, tzinfo])
.
.
+
+
+
+
+
+
10.
<>-
185
valueError. :
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)
, :
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()
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.
+
+
+
+
+
+
rnicrosecod- (
999999);
datetirne :
datetirne2
datetirne1 + tirnede1ta-
datetirne2
datetirne1
tirnede1ta-
+
+
1.
187
date ( J
datetime
>>> d = datetime.datetime(2011,
> <;l.date(J
datetime.date(2011, , 5)
time ( J -
+
+
date:
>>> d = datetime.datetime(2011,
> d.time()
datetime.time(23, 48, 23)
time:
minute] [,
second] [,
microsecond] [,
. :
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
-
188
1.
Python 3
toordina1 () -
1 :
weekday () -
6-
):
isoweekday () -
(1-
7 - ):
(,
isoca1endar () -
):
ctime () - ~:
>>> d = datetime.datetime(2011, 6, 5, 23, 48, 23)
>>>d.ctime()
'Sun Jun 5 23:48:23 2011'
utcoffset ()
10.
10.5.
calendar
189
calendar.
. ,
:
import calendar
n :
Calendar-
, .
Calendar([<nep
>])
n n n
no
2011
, n
Textcalendar-
n n .
TextCalendar([<nep
>>>=
>])
2011
c~1endar.TextCalendar(O)
>>> print(c.formatyear(2011)) #
LocaleTextCa1endar-
2011
n n .
.
:
Loca1eTextCalendar([<nep
>[,
201 1
< >]])
HTLCalendar
HTMLCalendar([<nep
HTML.
>])
201 1 :
>>> = calendar.HTMLCalendar(O)
>>> print(c.formatyear(2011))
Loca1eHTLCa1endar- n
HTML.
.
:
LocaleHTMLCalendar([<nep
>[,
< >]])
190
2011
/.
Pytho
SUNDAY.
n n
>). n
(
:~~~~~~
:
2011
. n
10.3).
..
>>> = ca1endar.TextCa1endar()
#
>>> c.setfirstweekday(ca1endar.SUNDAY) #
>>> print(c.fonnatmonth(2011, 1)) # 2011 .
10.5.1.
TextCa1endar
fonnatmonth(<o>,
<>[,
Loca1eTextCa1endar
< >[,
<
> J J) ~ . n
n ,
n .
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
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 .
rr(<>[,
w=2] [, 1=1] [,
=]
[,
m=])-
fonnatyear(),
, .
2011 .
4 , 2 ,
formatmonth (<>,
<>
[,
<True
Fa1se>]) -
L-
True
), .
L-.
, ~ .
cssc1asses,
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>[,
. L
.
:
2011
192
/.
Python 3
fonatyearpage (<>
[,
width] [,
css] [, encoding] ) -
L-
L-.
n:
width- ( 3);
encoding- . n
encoding L-n, <meta>.
n n n n
n. n
2011
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 :
>>> 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 (<>,
<> [ ,
<
> [ ,
<
>>> ca1endar.prmonth(2011, 4) #
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 (<>,
<>) -
2011
30
ca1endar (<> [, w] [, 1] [, ] [, m] ) -
. n:
w - n (
1 -
- n ( );
m-
2);
n (
1);
3).
n n n n
n. n
2011
n
:
prca1 (<> [, w] [,
1 J [,
) [,
m) ) -
=2))
ca1endar (),
, . n
2011
, n
n :
>>> ca1endar.prca1(2011, 2, 1, 4, 2)
is1eap (<>) -
True, ,
n -
Fa1se:
1eapdays (<1>,
<2>) -
194
1.
Python 3
weekday(<o>,
<>,
<>)- (-
, - ):
>>> ca1endar.weekday(2011,
4)
timegm(<OOe
struct_time>) -
, .
struct_time
gmtime () time. :
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 -
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
[' ' ,
'',
',
''
'',
''
'',
'n
',
'',
''
'.'
''
'']
'',
'n',
'',
'',
10.6.
t.imeit
. .
:
stmt ( ),
setup ,
stmt. , setup
timeit 1[numer=1000000J).
numer ~ .
r..
" '
......... "
.. " , .. "
! ...: t . . . " ' .. ' .. " " ' .......... ~ ., ' ' : . . . . . . ' .. " " . . . . . . , "
.... "
.. "
.. " " .. " ' " " . ' ' " . " .
+= 1
t1 = Timer(stmt=code1)
print("whi1e:", t1.timeit(numer=10000))
code2
"""\
j
10000 n n n ( 10.4) .
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
,
repeat([repeat=3] [,
numer=1000000])
repeat)
timeit()
. numer
t imei t ().
10000.
......... ,..... ,... ,, ... ,... ,......... " .... ,, ................. ,, ... ,, ............................. ,._,,.,,.. ,, ... ,,, .. ,, ......... ,t.''''''''''''''''''''''.:"''':,."'''"'''''''''''''
[. 10.5. l1n;~~~ ~t
;, ........................................................... ...... .. .... .....................;.;: ................................................. :.....................................; .... .
;
:.~
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:
, .
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. , :
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
string
[1, 2,
Python
3, 4]
, n , n
n . .
def ,
function, , n
def. , n
. .
n (
11.3) .
f
v
,,;;,,,;,~
#
#
sUJ111a
f(10,
;;;;~;;;;:;,,
20)
..;
n n .
,
11.4).
no
, (
sUJ111a (,
) :
return
def func(f, ,
"""
):
l.I.
return f
f m
s UJ111a ( 1 " " "
) # SUJ111a ()
(,
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 n
if n n n1.
, n
, (
11.5).
l ...............................................................
11.5. n ~tr or
........... ............. .................. ........ ........ ...... .. ..... ...................... ............................. ..................................................................... :
;.,
;;,,;,,
':
~ ;.;
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
,
. ,
. :
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
,
:
(**),
(
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
~:
11.
Python 3
205
.
, .
. :
.
, ,
,
=.
d .
, ,
.
,
, ,
. ,
, ,
:
#
#
#
#
#
=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.
#
#
rn:
207
1 4 9 16 25 36 49 64 81 100
u-
Stopiteratior..
_next_ ( 1,
( 1 u for .
_ next _ ( 1
u for ( 11.18).
next
+1):
#
#
#
#
())
())
())
())
1 (1 ** 3)
8 (2 ** 3)
: 27 (3 ** 3)
Stopiteration
:
rn:
, u 'l ~ '
, u- .
, . .
.
11.7.
u. , '
-
u.
1 1.19) .
return f
@deco
def func () :
return "
= 10
func ()
func()")
(O}".format(x)
. .: :~;, .;, : . . .:. . . . , .:. : :,:. ;.: . : . . . :. . . . :'. .;'.::(.:,.:;. "'................... . . . . . . . . :. . . . . . . .:. . . . . . . . . . . .J
def deco(f):
print("Braa
~.,.~,
208
1.
Python 3
func () deco ()
@:
@deco
, deco () func ().
- ,
. - .
:
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,
", .
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. :
(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
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.
. glo
.
UnboundLocalError
),
11.25) .
............... ,......... ,................ ,........ ,.......... ,.,.,., ... ,.............. ..,.,.,. ....................................................,... " ....... ,....,., ... ,.. ," ......... " ........... " ......................,.......... ,..... "., .......... ,, .. ,......... ,..
~- 11.25. n n n ~
'
:..................... :......................................................... :.......... ;.: .....:..... :.. :.......... ;:.:.:.:::.:::::::.;,;,:,,;:-... :.'.'.i.>; .=;,;;.~:: ..... :: ......... ;.: ........... :................... :..................... ;:,.. ..:........ ~
#
#
#
#
printlglo)
glo
glo
~25
lO
funcl)
#
UnoundLocalError:
ll!!
!1
m:
local
variae
'glo'
I J ,
(
:'"'''"'''"""~"'"''''~
......................... .............. .... .......... .......... ................................... ...............................,......... ... ..... ....
~
global.
11.26).
~~~.~~
-; '
,~
: .... " ... ". ''" .. " .... " ........ "' . " ...... ,; ;, ;;, 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).
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).
#
#
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
():
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_
"1",
annotations
'1',
'':
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
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,
>). , 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).
. . . . . . . . . . . . . . . ,. . . . . .,. . . . . . . . . . . . . . . . . ,. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . , :
;.,,.,;:.~
....................................................................:....................... ;
50
n n n , . n
tests.py
n (
;.
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""'''"'"'""''""''"""""''""'""'"''''''"'"""""""'"""""""'""'"""""'""" """"""""'""""'!
.......................................................................... :::.. :: ..;,: ......................................... ;............................... :........;,,;,,,, .......... ~ ................................................................... .
;,,,,,,,,,,,,,,.,,,
tests
sys
putl)
import
. , n
. n ,
\1 n ,
_ import _ 1).
import 1) ( 12.9).
li....
12.9. !i!I!I~~ ....
...........:...................;..................... ;.... .... ...:.......
.. ... ;;; ....
....... . . . . ..
~
:.~
~;
~.=.~~.:
tests.py
;,;;:~ ;.;;;,,,.;;;~
m=
import
printlm.x)
#
#
ls)
tests
putl)
,
(
_ dict _,
dir 1).
12.10).
:.
""'"'
12.2.
.keys() ))
from
n n
220
/.
Python 3
from
<
>
import
[,
from
<
>
from
<
>
<
<
.,
. ,
floor 1)
as. pi
math. ( 12.11).
..
:~~:.~ .~:
.. ..
~:::.'.::.::..::.:.
r...
pi
,
:
from
math
12.12).
math
pi
floor ()
, ,
, . , ,
,
. . , , .
from
import.
12.13.
;~
module2.py
12.14.
module l.py
12.
221
................................................................ .....................................................................................................................................................
~
12.14. module2.py
module2"
"
12.15.
12.15.
"
"
"
module2"
modulel"
module2"
, n n
. , n
s.
, n n.
module2.py. n n n n
u
import. u n .
_all_ , n
n
: 12.16. _all......
............................................................................................................................... ................................................................................................................................................... ;
""
n (
12.17).
12.17. n
........................................................
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
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"'''''''"'''''''''''"'''''~''"'''''' ''''''''''''''''''''''''''"'''"'''''''''''"'''''''';,,,,,,,,.,",.,,,.;,,,,.,,.,.,,,..,,,.,,,.,,,,,..,,,,.,,.,.,,.,.,,.,,.,,,,,,,.,,,,,.,,,~.,,,,,,,.,,,;,,,,,,,,,,.,,,,,,,.,,,,,,.,.,,,,,.,,,.,,,,.,,,,.,,.,,,,,.,,,.,,,,,,,,,,,,,,
-*-
#
#
sys.pa~h.append(r"C:\fo1derl"!
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.
>)
tests.py
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
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
'
;,.;,
l.py, module2.py
...................................................................................................
;;,,,;;,;~
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;:,:;,
;~
;;~
:.';;,;;,'~: :~;
(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:
n, n
:
8 . 1349
import
n n
226
/.
Python 3
import
*:
from
n n n.
_init_.py
_all_ n
from import *
, n n
_init_.py
folderl \folder2\:
main.py
12.23)
n .
. .
:............... :... :.. ... :........ ::... :.. ,.:; ... :...............:. :.~.:. :..... ,,,,:,;:.-.;;;,,:,; ''..;,;,;.;;:........:.;;;",;;,;,;~~;.;,;;::.;.~;- .:=;;;,;;=;;;: ..... :.. ;,;: .........................................................................................i
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
. n
import.
module3 .,
n.
12.24.
12.
227
......................................................................................................................................,............................................,.............,.....,...............................................................,...,.................... ,
f 12.24. ~ n~ module.py
:"" ...... " ... , ." ",,.,,, , , , . , , .. " ,, . , .~, .. ,, , .. ,, " .. ,, .. ,,,;"," , , ,, , ... ":,,,. ,,, "~.,, ;,,,, . .,, , ,,, ,".,,, .. ,,, . .,,, .. ;,:, ... ,;,;, '" ,; . ,.:, ". , ,; .;",, .. ~. "'""'''"',;; . .,, .. ,;;:",;;; , oi. ;,, ,.,, , ,',.,,,, ,,, , ... '", ,,.; . , "",, .. ,,,,", ... . :;,, .. ,,, ... , .. ;
# 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--,
~; :~
~~
folderl.folder2.module2
folderl.folder2.module2
folderl.modulel
folderl.modulel
Pytl11
import ,
znopm.
, .
module.py ,
:
n
n n
n
folderl\folder2\.
module2.py module.py.
mai11.py (. 12.25).
n, n module2.py
n ,
, n.
n , ,
n
from:
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
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
<>) - .
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
Classl
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""'""'"'"'''"''"'"'""'""'"'''''''~
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
- >
Class
_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 >,
+ _ 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
:
_getitem_(self, <>)-
. for,
, . :
class MyClass:
def
init (self, ) :
self.arr =
def _getitem_(self, index):
return self.arr[index]
13.
237
def
de1item
(se1f,
<n>)--
de1
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.
/.
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
();
n n
float
(self) -
float ();
13.
239
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 :
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~ " '~" ""'""' " "' ' ' " "" ._''" ' " ""'""
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' ''' . ' ' . " " '." , , . . . . : .'.'.' ' . . . . . . . . . . . . . ' ' , '' , . ' . . . . . . . . . . . , ' , ' ' " . . . . . ' ' . ' . . . . . . . . . . . . . '.. , ....
!:.~~~~~.~.~. ~.~:.~~~.:. ~~~~~~.~:.~~:~,~~ . .~,. . ..,.:~...::.::....:..:.. :.~...}.:... :.:...:: ...:.:..:.:....:.:,,... ....... .....................................................................!
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).
#
#
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()
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
13.
245
, .
_slots_.
. ,
:~:''
_slots_,
AttributeError ( 13.19).
: ' '. : . , . ' . '' ::" , ''."!' ': '''''.':.< ~-.. .:.:.
t r 13.19. . $iib.
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
,
, .
<>
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()
deleter (),
13.21.
........................................:..........................;;,,,,,.;,, ..:. ................ ..............;, ............... ,,,;;;.,,,,.,,;,................. ,,.;;.,, ...... ._ .. ,; ........... ..................................
:
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.
()
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
- ,
. ,
. , . . .
;
- ,
. , .
:
):
return
ValueError, :
index ()
248
/.
Python 3
14.1.
try. :
try:
<,
[e>:cept [ <1> [ as
<,
>
< >]
]:
>
...
except
[<N>[
<,
as
<
>]]:
>]]
[e1se:
<,
m,
>]
[finally:
<,
>]
, ,
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 "" .
, .
,
") .
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
14.6.
~~.l~o.II,>~>!"'~'''"''"'"'''"""'''""''"''00"''"'~0>":~.'"~."":'''"''!~'.''":"'"'~'~''000"''""'~''""''.''M0.'!"'!''''~~~='''~~.'!.'""''"'''''""'''''.'!'!'"'~'00"'!'"'"'''"'.".'''""""''"'''"''''''"'"''"'"'''''''''"""''''"''""'.'''''"'"''1,
14(fi . .. . . . .. .
..
:. :~~.;~~:: .-.~~--.....:;,;;,,,;,,;.......... ~;.:.:;, .. ,,,,.;;; ....;; ..~:;;;;,~j;;~:;,,;:,:;;;;~:;;;;~;.,,;.,.,;,;;;;~;~'.;;;;;";,: ....... ;....~; ....;;.. ~ . ~;;;,:;;;;,.,.;,.;,;,,;';;;,;,;=;,;,;.~=..:,.;,; .. ;... ,. ;...... .:: ... :.............................. .- ..:... :........... :...... :................:;
:
<class 'ZeroDivisionError'>
Value: division zero
Trace: <traceback object at 0030>
ZeroDivisionError: division
zero
File
":\ \book\ \
test. ",
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 , , .
(
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).
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
:")
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 .
~" " ' ' " " " " " " ' " ....... ' ' " . " '.' ............. " ......... " ' '' .... ' ....... !~'-'.' ... '' .... " ....... ' " ..... " . " ' ~ ' " ..... ' ........ ' ..... '! .......... ". ... " ' .......... " " ' " ' .............. ' ' . '.
-~ ;
;~~;
;;
with open("test.txt",
open ()
:. ::. ; ,,; ;;:.; :.~:. '" ,; ,;:... :;; ;, ............. ' ...... ' ..; ..........:' ... '" . ' .......... " ........... .
.. .............. 1;
encoding="utf-8") as f:
"",
f.write("Cpoa\n")
...
test.txt
~ .
wi th.
, , .
14.3.
Pytln .
14.12.
~~"'"'''"'''''"'''"'""'.'""."('.'''("''~'"''"''~~.'"''''''''~".''~'.''.'.'~"~''.'("'""'''"'.'~~-"'""''""''"''"''"''(~''""'"""''""'"""'"'''""'"''''''"''"'"+""''"'"'"'"''"'""'""'"'''''''''''
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- ;
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:
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 (" ")
:
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
258
1.
Python 3
ValueError,
zeroDivisionError. ,
from . from
_, :
raise .
assert AssertionError,
False. :
assert
<
~>[,
<>]
assert :
i f _debug_
assert:
try:
=
-3
_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 (),
IOError:
260
1.
Python 3
.
.
os. path.
abspath ()
,
. :
,
. :
>>> # 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.
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 .
15.2 .
................ ......................................................................;,;.. ... .... .................................... .... ....... :;;,, .. ;;,,-..:,; ....; ...... ::......... ...:.... . ...
~
;;;
; ;;
,;,;;,;,,,
.............................,........................................ ;
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).
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
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 :
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.write("Cpoa")
>>> f.close()
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.write("Cpoa")
#n
> f. close ()
n encoding:
for line in f:
print(repr(line))
'\ufeffCpoa'
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-32
n , n
nn . n , n :
'
>>> with open(r"file.txt", "w", encoding="utf-16")
as f:
f. wri te ("")
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
Python
n , n
. :
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),
. ,
, ,
. ,
. :
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. close ()
flush () - ;
fileno () - .
2, . . stdin, 1 -
stdout, 2 -
stderr. :
> f.close()
+ truncate ( [<>]) -
. . :
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
, .
:
>>> f.readline()
'String1\n'
> f.tell()
9 (8 + '\r'),
8 !!!
>>> f. close ()
, ,
:
>>> f.close()
io.SEEK_SET - ( );
1 -
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 ()
-9
>>> f.tell()
7
>>> f .close ()
:
+
+
+
narne- ;
mode- , ;
closed- True, , False . :
>>> f = open(r"file.txt", "r+b")
>>> f.name, f.mode, 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". :
buffer- .
.
. :
>>> 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)
> os.close(f)
272
/.
Python 3
rd.(<>,
<
>)-
. . :
> os.close(f)
write (<>,
<
>) -
. ;
+
+
close (<>) - ;
lseek (<>,
<>,
<>)
<> <>.
. <>
:
os.SEEK_CUR
1 -
>>> os.lseek(f,
os.SEEK_CUR) #
>>> os.close(f)
+
+
du(<>)- ;
fdopen
(<>
[,
<>
[,
< >]
]) -
open ( ) . :
>>> fd
> fd
os.open(r"file.txt", os.O_RDONLY)
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 "". ,
, :
getvalue () - "" :
>>> import io
#
> f = io.StringiO("Stringl \n")
>>> f .getvalue ()
#
'Stringl\n'
>>> f.close()
#
+ tell () - n "";
+ . seek (<> [, <> J ) - 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()
>>> f.write("String2\n") #
/.
Python 3
nI
> f.getvalue()
'Stringl\nString2\n 1
> f.close()
. "",
n . :
>>> f = io.StringiO("Stringl\nString2\n")
> f.read()
'Stringl\nString2\n'
>>> f.seek(O) #
"" ,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
""
. ,
. .
, . :
> f
, .
\n.
. :
> f
>>> 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
().
+
+
flush () - "";
truncate ( [< > J ) -
"" -
. :
276
/.
Python 3
, "" :
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()
, (
''
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 ).
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:
. (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.
n ,
. , nn.
n,
IOError. ,
WindowsError. n
Windows
C:\book\test:
file4.txt
<
>)
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")
WindowsError.
Windows
>>> os.remove(r"file2.txt")
>>> os.unlink(r"file4.txt")
os .path n , n n
, n . :
. ,
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
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'
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:(';~~-~~~
.................... ;,;,,,;;;,,,,,,;.. ,;,,,,,;,, . :.................'.; ...'.;;;,,;,,.,,;,;;,,;,,,,,;,,,,;;,;,;;,,,;,,,,,,;,,,, .........=::.;:-:;......... : :::: ..........;......... .........................
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.7.
os .path:
. :
282
/.
Python 3
> os.path.abspath(r"folderl/file.txt")
'C:\\ook\\folderl\\file.txt'
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'
!!
, ,
. , .
. . ,
. :
>>> "C:\\temp\\new\\"
'C:\\temp\\new\\'
> r"C:\temp\new\\"[:-1]
'C:\\temp\\new\\'
>>> 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')
nonnpath () :
15.8.
, ,
fileno (),
stdin, 1 -
2,
. .
stdout,
2-
std~rr.
. ,
. ,
284
/.
Python 3
, .
(
j1'~;;:~~~1:5i':h~p~~~ri~~~~~~;~6~ti~';~
15.6).
. ..................................... ;.
: ,;,,,,, < ; : .......... ~ :: :.;,.,;.:_.;;;,,:;,; ;.;,... ;;,..,,,;:. ;:.: ..:;;;;..... ::,.. ::: . ::;. . .-;;,;,,, . :.-~ .............. :.. :.;.. :: ... : ...... ;.......................................................... .
"")
>>>
")
rint("
#
#
#
#
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~~~~~
;::.:. ;~;:.=......... :.:~ ...... ::.... :..~;,,;;; ..~ .. ~-~~- .. ~~::.~~::.~;;,;,-;. ~~.: ..~.;;:
#
#
#
#
#
#
#
#
#
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 ...............,, .. , ...................................................; .................................; ... : .... ;;,,,,,, ............ : ............. , .. ; .................. ;:~ ................;,,,,,,;,,,, .......................................... ;... . ..................... "'
: \book. n
file.txt,
cd
n :
< >.
tests.py
n nn
file.txt,
n :
file.txt
nn.
, n
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
~.;~
.. :.;......
;,,,;;
;,;;,;;;,,;,,,,,,,~
..:...;:_.,,,;,,.....................................................................
%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) - . <>
. . :
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!
~........................................ ;.... ' .. :.". :. ;:::;' ;; :;. :: ... :..'~=.... ,;;; .. .::' ;; ,:,,; . : .... :' :: ....'. ;, ...... ;;; ~................ ; ~ :~.; ...:.;~:; ;; ,',, .:.': :.:; :........ ; ..,:, .... '... ...
#
#
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.
Unpick1er(<a>[,
pick1e
. :
.
(
3).
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 (<
>
+
+
+
r -
flag :
w- -;
- ( ). , ~
;
n-
. , . ,
open ()
. :
c1ose () -
t.
+
+
+
#
#
#
#
#
#
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;
. 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")
, 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
isfile (<> J
True,
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.
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
. ,
. :
";"
.
( ) .
<Enter>,
SQLite:
"
SQLite
.
.
/*
* 1.
. .
.
, . :
sq1ite> --
sq1ite> /* */
sq1ite> SELECT sq1ite_version(); --
3.7.6
SQL-
16. SQLite
295
SQLite
/* n SQL-I
*/
.exit
.quit.
16.2.
SQL-:
CREATE
< nl>
TEPORARY]
[< >.
[<n >]
[<n>],
[< ~>]
[<>],]
... ,
< N>
[< >]
);
CREATE TEMPORARY,
. :
. taes
. sqlite.exe
SQL-apoca:
sqlite>
... >
... >
... >
... >
... >
trnpl
trnp2
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);
>),
( ,, ,
.). ,
.
trnpl
296
/.
Python 3
"sqlite_",
. ,
SQL.
, u t :
sqlite> CREATE
sqlite> .taes
t
tmpl
tmp2
"tale"
(polel);
, :
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
typeof () .Li.
~;~:
NULL- NULL;
;
INTEGER-
+
+
+
REAL- ;
- ;
BLOB- .
INTEGER PRIARY (. .
), NULL.
NULL
. :
sqlite> DROP
L tmp;
NUERIC INTEGER.
S. ,
INTEGER,
. , , NUERIC,
:
INTEGER;
- REAL.
298
/.
Python 3
sqlite> CREATE
tmp3
(1 );
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 :
, n
n n. , n
NULL;
DEFAULT <>- n , n
, n n . :
sq1ite> CREATE
tmp3
(1)
(1,
VALUES (800);
FRO
tmp3;
80010
511204
sqlite> DROP
L tmp;
n <> lt:
CURRENT_TIE-
URRN_IS-
UTC
::;
UTC
-- ::.
sqlite> CREATE
... > t
DEFAULT CURRENT_TIME,
... > d
DEFAULT CURRENT_DATE,
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
L tmp
tmp
"D"
FRO tmp;
"D"
FRO tmp;
sqlite> SELECT
--
sqlite> DROP
L tmp;
t UNIQUE
NOCASE
[< >]
(<>)
, ,
10
20:
PRIARY
[ASC
1 DESC]
[<
>]
[AUTOINCREENT]- ,
NULL.
INTEGER,
NULL
. :
sqlite>
sqlite>
sqlite>
sqlite>
);
111
212
"");
111
213
sqlite> DROP
L tmp;
NULL,
. , ,
, .
, AUTOINCREENT. :
300
/.
Python 3
"");
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
2121213
sqlite> DROP
tmp3;
n <~ >
:
PRIARY
(<
>)
[< ll>]
n 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>,
<>]
<2>,
. OR
R,
INSERT. :
FAIL, IGNORE
<> (ROLLBACK,
REPLACE).
. ,
,
VALUES.
. ,
INSERT
. , ,
n n
CREATE
L.
):
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
site
,
, .
,
. .
SQLite.,
passw.
user
id_user ,
id_user
. ,
NULL. .
site. id_user id_rur
11 user rur. .
user rur. ,
. , Y'IWe .
(, )
SQL-.
, - .
r .
, .
:
'
' N'
');
,
:
21
' N'
'
N'
"
' N'");
'
'' N''
');
1.
303
SQLite
( UNIQUE ), SQL . ,
REPLACE
OR. 2:
21
I
' N'
REPLACE INTO
[(<l>,
[< >.]<
<2>,
... )] VALUES
(<l>,
>
<2>,
... );
3:
'');
11
21
!
16.4.
UPDATE. :
>
OR <> (ROLLBAC,
FAIL, IGNORE REPLACE).
. SET
R,
. ,
WHERE. , <>,
. <>,
.
3:
id_rur=;
11
21
I
DELETE
[WHERE
FRO
DELETE. :
<>];
304
/.
Python 3
, .
, .
3:
rur=;
11
21
.
, SQL- VACUU.
, SQL-
16.5.
. ,
. ~:
<> :
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
. ,
,
NULL , . .
. , PRIARY
UNIQUE.
iq
site:
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
1:
WHERE id
rur=1;
11
*.
. rur:
sq1ite> SELECT *
FRO rur;
11
21
SQL- SELECT .
, :
sq1ite> SELECT 10 + 5;
15
,
,
AS:
(70 * 2) AS expr2;
. site
rur:
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
n :
AVING. n , WHERE,
nn . n ,
(),
n. , ~:~n1 :
COUNT (<>
*) -
1 n.
FRO
site;
MIN
(<>) - n.
(<>)
h.
sq1ite> SELECT
3000
AVG (<>)
AX(iq)
FRO
site;
- n.
1.
307
SQLite
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
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,
:
. ;
, :
JOIN
INNER JOIN.
JOIN, : CROSS
JOIN:
. ,
sqlite>
... >
... >
... >
... >
1:
ON
USING:
1. SQLite
JOIN
309
, .
, ,
"", . .
. ,
. :
<61>
ON
LEF
[OUTER] JOIN
<2>
<61>.<1>=<2>.<2>
1 USING
(<>)
, ,
<1>, <2> (
<62>
NULL). -
16.8.
WHERE
WHERE AVING. ,
.
:
= == -
. :
sqlite> SELECT *
FRO rur
WHERE
id_rur=1;
11
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;
NOCASE .
. :
sq1ite> SELECT
010
!=
<>-
''
'',
''
''
COLlATE NOCASE;
+
+
+
+
<-;
+
+
rs NULL ISNULL-
>-;
<=- ;
>=- ;
BETWEEN
<>
AND
NONULL- ;
;
<>- . :
BEWEEN
1 AND 100;
IN (< >) -
. :
sq1ite> SELECT
1
sq1ite> SELECT
''
IN
('',
'',
'');
''
IN
('',
'',
'');
LIE <>
[ESCAPE <>] -
%- ;
- .
" . ,
,
% :
16.
311
SQLite
LIE
'%word%';
1
, :
LIE
'test%';
LIE
'word%';
, :
LIE
LIE
'%wor%d%';
. ,
% ,
.
, %
_?
. ,
ESCAPE
<>:
LIE
'10%';
LIE
LIE
,
. ,
true;
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-16be.
866 Widows-1251,
.
UTF-8
. , ,
.
UTF-8.
. n
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. SQL-:
<SQL-anpoc>
QUERY PLAN
, n n n
. , n
. n nn n n n
site.
n n n n, n ,
- n:
" , n n
n n , n.
n .
n . n
CREATE INDEX.
SQL-
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, :
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.
[<
>.]< >
, SQL- VACUU.
sqlite_statl.
.
, SQL-
ANALYZE ..
ANALYZE [ [<
>.
SQL-
] <
>]
ANALYZE sqlite_statl:
rurii
users 111
16.1 .
SELECT ,
.
:
CREATE
1 TEMPORARY]
[< >.]<
rur :
1.
SQLite
315
11
21
I n
SELECT,
INSERT.
INSERT [OR
[ (<l>,
INTO [<
... ) ] <n SELECT>;
<>]
<2>,
~>.]< ~
tmp_rur,
:
rur<;
11
21
, <>,
. ROLLACK, R,
FAIL, IGNORE
REPLACE
, .
REPLACE-
IGNORE
IN.
WHERE.
"r":
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
, :
21
I n
41
n, n n n .
, n ROLLBAC.
n
n, n n .
n:
'');
1.
317
SQLite
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
. ,
,
#
#
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
4.
5.
6.
-.
.
17.1.
connect ().
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")
17 .2.
#
#
#
#
sqlite
rn ~
~
rn ~
DB-API 2.0
-. n n .
- n n cursor (). n
n n -:
+
+
close ()
- -;
. n :
320
/.
Python 3
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:
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, ,
SQL-apoc J:!,
. SQL-apoc,
, ,
. ,
apoce :
- ;
: <> -
{"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 ( ) :
id_rur,
try:
cur.executernany(sql, arr)
except sqlite3.DatabaseError as err:
print (":", err)
else:
print (" m")
con. commi t ()
#
cur. close ( )
#
con. close ( )
#
input ()
3 {
DB-API 2.0.
17.1 ).
17.
SQLite
323
Pytho
lastrowid- n n INSER
execute (). , None.
n :
rowcount-
n. n
. -1;
description- n
SELECT.
n,
None.
SELECT * F'ROM rubr,
n, n SQL-anpoc
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 () :
Stoplteration
for
next _ () .
n n - n .
n rur:
(id_rur,
n))
11
21
3 1
41
.,r
n n n
, n.
n . , ,
n n arraysize -.
n n
n, n
n. n , n n. :
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 -
( )
. . .
. :
(3,
'
'),
[]
row_ factory
, :
def
< >(<->,
<>):
#
return < >
user
{}
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).
;~;;;,,,,,,,.,;
.............. ;.
Windows-1251.
SQLite ,
testdb.db
u :
'n
rubr'
17.
UTF-8.
SQLite
Pytho
327
11
text _ factory
OperationalError.
,
. , ,
bytes 1)
17 .4) .
..... ,......... " ..... ' ......... " ............. " ... ,............................. ,.......... , .............. : ...,.. ., ...... :,., ..... ,.,,.., .... ,.. ,. .............. ,.,........ ...................................... ,............ ,........ ,.. : ................. ,.......
"'"~
~............................. ;."''"'""'''"'"'''""'''"'";;,;;:. ~;.;::-;::,.;,,,:,; .........'...... .- ; ........... ;,;. ;~;.~.;-:i.;; : .............. ;........=;,; ........... ;;,,,,;;,;.. ;,,,;;,,;.:.=,;-.....=.: .........;.............;................. ;, ...................... : ;
>
>
>>>
>
str 1) .
.
(
17.5).
!''J1~~~~~1r:s~y~~~~~~~~-~~~~~~f~~~~~~~y~;4~~:ri~~~;~~J~~~
::.. ;.. '' ... '.... ': .. '...... '' ... '...... '...... '.. '.. '.. '.. ;, ': ... ; .-:'' ''" .. '.' ';;: ..... ;;........ ';' ;; ....;:.. >..... '' ... '.. :.'i "'" : :. ;... :" ... ; ;;, ...: i;. ;, ;... ',; . ';. ~ ... ;;.... ' ....... ;...... ;.
17.4.
...................:.!
"1251")
.
,
counit
1)
DELETE),
, .
CREATE
L,
VACUUM
. .
rollback 1)
. ,
(
17.6) .
......~ ........ ; ...................................................................... ~ .....~.; ............. y...............................................i ..............y ;y ........ ;;,.... y...........; ... ,; ... y............. ; ............... ~; ............................ y.,;, .. , :
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
. n n
n
isolation_level, n, n
n (
17.7).
17.5.
ORDER
ORDER
COLLATE.
SQL-anpoce n n n
create_collation () . :
create_collation(<Haae
<
SQL-apoce
>)
>,
17.
SQLite
Python
329
+
+
+
1 - n ;
- 1 - ;
- .
,
. .
, ,
( 17 .8).
'
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
#
def myfunc(s):
return s .1ower ()
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:".'''"
:. "' :. '., :. 1" ,, ; '" 1"'' 1.: ' .. ' 11." ..... '. i;.; .=..: ....... ;, .;'1'. ,,;:;: .:
: .
,; ...... ;;.,,,;.'": ,; 1:. ;;i; i.' ,:.;' ;; '; ' .. ;;.. '
~:
.:'.'''''?::::'''')'.''''""'!'''''":''~''''
'''''""''"':
'
.......... :
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
apoce
SQL-
create_aggregate ()
. :
create_aggregate(<Haae
<
SQL-anpoce
>,
<m
>,
>)
u .
( ).
:
332
"''~":"''''~::."".
/.
Python 3
..
i ......." ................................. " ... ,",,,,";,:,;....~....", ...,. ........~ ... ;,;;;;,,.,,;;:"; ...;,;;.. ;, .. ~; ...... ~ . ~; .............: ......c.-.; .. ,. ... ,..........~ .... ,.... ,"........................... "......................................................................... ""''''''i
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
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).
class Car:
def
init (self, model, color):
self.model, self.color = model, color
334
def
/.
Python 3
# 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
."-'""
mycar
n
L
sqli t. PARSE_DECLTYPESCREATE
n SQL-anpoce n n
. n
"
1):
n (
sys
class Car:
def
init (self, model, color):
self.model, self.color = model, color
........... ,...........
17.
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)
_converter)
detect_types=sqlite.PARSE_COLNAES)
"
cars2
17.15).
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).
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.
337
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).
''""""'"'""'""""""'""'""''''"""'""'""""""''"'"'"''"'''"''"''"'''"'""'""""'""'"'""'"''"' ,.. ,"
i :. ;;
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 :
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.
.
:
URL-apeca:
<scheme>://<netloc>/<path>;<params>?<query>#<fragment>.
, . .
.
URL-apeca
18.1.
~~~~;1-a:i"~~~~p tiRL~;;;t~~;;~~~~;~;~~;i;;;;<i'
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .!
18.
341
urlparse () ,
, URL-apeca.
. :
scheme -
. .
. :.
netloc
1.
. :
+
+
hostname -
. :
None;
port- . : None. :
>>> urlohostname, urloport
( 1wwwadmin.ru 1, 80)
path- . 2. .
:
params- . 3.
. :
>>> urloparams,
(1st 1' 1st 1)
url[]
query- . 4.
. :
fragment- . 5. .
:
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;
getur1 1)
- URL-apec. :
~~~~;~:2~-iri~~~~~4:~~~~it~4:;;;;;.~~~:,;-:::~-:;::--------;------
~ ~ ~
[,
<>[,
. . . . . . . . .!
:.~.............~...~.;.;, .. ;.~ . ::.. ,..:;;,.. ;;..~~; .,.,.. ,;.:.;........ ;...:....;;,,,;................. ;..~;.,,;;,;;~;,~.;;", ;,; ....... ;,;;;:.............; .............................. :....................................... ~
ur1parse ()
< >]
J).
'var=S',
'metka')
'var=S',
'metka']
ur1sp1i t 1<URL-apec>
Sp1itResult
URL-apeca. n :
. n u
ur1sp1it () n
18.3.
;;
. . .
.
.....-........... ................................... ...................... ... :......................
................ ... .............. ...... :..................... ~ ..... ........ ;~;..............; .....,;,,,;,,.,,;, .... ,;.;,, ... ........... ............. ..,;:;
;
,.,,.,~,
;;
:;
~ :
"'''"'''';;;
18.
343
urlunspli t 1<>) (
~-:,~;;~~~;1:~~~~~~~~~~~~;~-~~~~--~1~;ii~<:
18.4 ).
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .;
;.............................................. ;............................. ;.... ., .......... ~ ........~ ............................; ........~ .....=.;;;.,.;; .;.............. ;...~..... : ...... ;.......................... < : .............................................................,j
18.2.
'var=S',
'metka')
URL-apec .
, <n> .
n , n=. n
]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]
True,
n,
n, .
n n . n strict~parsing
344
/.
Python 3
True, ValueError.
. encoding .
errors- . :
.
, . :
parse_qsl(<Cpoa
>[,
strict_parsing~False]
[,
keep_ank_values~Fa1se]
encoding~'utf-8']
[,
[,
errors~'rep1ace'
Jl
urlencode ( 1 url1ib.parse. :
urlencode(<Oe>[,
doseq~False]
[,
safe~'
'] [,
encoding~None]
[, errors=None] 1
,
.
, .
', ,
18.5.
'str~%D1%F2%FO%EE%EA%E0+2&var=20'
18.
345
doseq ~ False.
18.6.
18.6).
~~~~
............................... ; ................................... ..
113
urllib.parse:
quote 1) ~ u nn. ,
(_j,
(.)
(-) .
%20. u:
quotei<Cpoa>[,
safe , .
1. encoding
, errors ~ . :
Windows-1251
UTF-8
'%DO%Al%DH;82?;01%80%DO%BE'O'iiBMDO%BO'
> quote_plusl"/-nik/")
rrors=None
l)
346
1.
Python 3
'%2F%7Enik%2F'
>>> quote_plus("/-nik/", safe="/-")
'/-nik/'
quote (),
, . :
qut_frm_ts(<
>[,
safe='/'J)
unquote () - %nn . +
. :
> s = "%DO%Al%Dl%82%Dl%80%DO%BE%D0%A%DO%B0"
>>> unquote(s, encoding="utf-8")
''
encoding='utf-8'] [, errors='replace'])
unquote (),
I(!
. :
unquote_to_bytes(<Cpoa n
>)
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
'file. html' 1
'f/file.
html')
n n , .
, .
18.4.
L-
L- n. n, ""
(<) ""
. n n
(> ),
>. n
xml. sax. saxutils:
si<>[,
L-
. n <> n n
L-
. :
111111
348
>>> escape(s)
'&<>" '
>>> escape (s, {
""
11
11
"
"&nsp;"
/.
Python 3
} )
'&<>"&nsp;'
quoteattr (<> [,
n.
, n.
, n, L-,
. n ,
. :
unescape (<> [,
<>]) -
L- &, &1 t;
>
. n <> n
n L-
. :
""":
>>> unescape(s,
'&<>"
<, >
& L- n
rue,
"&nsp;
Python 3.2
escape
L- (
18.8).
n . n
(<>
[, quote=True])
html.
18.5.
http. client n n
HTTPS.
no
n n GET, :s HEAD.
, n n , n
HTTPConnecoon.
18.
349
:
HTTPConnectio (<>
[,
<>
n n. n
n. n , n n
80.
n . :
> con2
HTTPConnection("test1.ru", 80)
request ( 1
request(<Meo>,
<>[,
body=None] [,
hdrs=<>])
n 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,.;,;;,,;,,!... :.... ;,;,, ~:..... ;;,, .. ................................. .
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
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'.'~~..~:~:~~,~~-~:~~ ~:.::,~~-~~,:.~:~.~:-~-:::.~:~.::~-:~~-~;,::::;.-~:~::~ .:,~:::~;:-::
=. . . . . . . . . . . . : ....: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
...............
~ ...................... :
, , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .: ;
con = HTTPConnection("test1.ru")
con.request("POST", "/testrobots.php", data, headers=headers)
resu1t = con.getresponse() #
print (result.read() .decode("cp1251"))
n. n, n n 1
$_s.
, $ _ros n
.
n :
. ,
None
n. :
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')
304,
, .
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
>>> 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
/5.2.4
>>> resu1t.msg.get("X-Powered-By")
1
/5.2.4
~. , None
. RJiep:
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
''
> 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 (), :
. ,
,
. , . :
>>> res.read()
''
.
, ,
(\n),
, ,
, .
, . :
Python-urlli/3.2
. 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.
+
+
close () - ;
geturl 1) URL-apec n . nn
1 , URL-apec n
n URL-apeco, n;
info () -
, n n
n http.client (. msg ). :
+
+
code- ;
msg- . :
>>> res.code, res.msg
(200, '')
n n n GET s (
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>[,
[,
URL-apec.
,
POST
GET,
POST Content-Type
app1ication/x-www-form-ur1encoded.
. cookies.
.
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
18.7.
"MySpider/1.0".
. n
, .
Content-Type
<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
1).
18.14.
'" ... ". "''' .. '""""."'" . ' .. '." .. '"."".' ... ' "' . "." ..... " . " '" ' ... '' . '' . '"" ".'." ..... '' .. '."""" '' ''"" . ~ '" .. '" ...... :... '' ........ -~ ... " "!" "' ....... '"! . ............................ ,....... '' .. '''." ............. ~ .............. '.
f 18.14.
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.
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,
11.
362
CkkNext to COitlnue.
(::t >
.
19.1. PyQt.
J 1 cancd
Licene Agreemonl
Ple- revlew tho lcense terms efore lnstoik>Q PyQt.
Llmltod
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 ~;
Extensm~
c~syou-hto
QScWJIIa
~:
E]Qtr~.rotime
EJ Doveloper tools
EJ Qt developer tools
e]Ex1111"4)1es
i"''''''' ~''
000
00
00
~ "'"'"''''\00f"'
.. '
PyQt. War 3
19.3.
'''' "t:''''''''l'''''..'.0"'~'0~oo
>
QtCor~.Q_VERSION_STR
'4. 7 .1'
364
11.
19.2.
19.5.
PyQI. 5
,
" , !".
19.2).
...~,., ...................\.'''''''''''''''''''""'''''''''"'''"''""'''''''''''"'''''''''\'!' .. ,, .. ,, ....... ~, ..,,............. ... ,...., .........................~"''"'"'' '"'"''''''''' ''''''''"'''"''"'................... , ................ ,, .............
:~
f...........
19.2. n PyQt
....................................,, _.;, ,.;..,,.......................... ........
;
wi ndow.resize{OO,
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, .
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
")
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 .
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:
,
.
368
11.
. .
- (
19.2
19.3).
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 ~ ;; ;;,',;;,;:,~
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)
" )
self.button.setDisaled(True)
if
test.pyw
(.
19.7). n
t n n n .
n - n t .
19.7.
,)
MyDialog,
19.4
QDialog.
. ,
n-- n .
MyWindow.
19. PyQt
371
MyWindow ,
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.
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
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'*
u.t-
"':8 Tree..,...
fI ...,...
JIDeoum..,...
~;:g
...,".
/1 -;;._~- ....
1
~~
..i
----
[lu.tllo'od9et
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
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 :
loadUi ( >. :
<n >])
, .
n n n , n,
Destgner objectName.
19.5). n Qt
374
11.
self ( 19.6).
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_())
self
setupUi (}
19.7).
.~:~~"~".''<!-!''.'.:"~'~'-'"-!:''"'"':"~'"""'"""~~~:'"''~'~".''"~"'''''''"''"'""'"'""~
p~tt1;.1'
.'
,!
~~;;;;~; ... ;~~~.;~;;,.,;;;,.,.;;' .:.:;;.= ~: = ; . . . . . . i....... :...........'.i .......... ,;.,, ... ,;........;J
, : . . .
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).
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
19.9).
l:'~-~~~~~:;19~9;~~~~~~:;;~;~~~~~::~~~;;~1
t.; : .... :..................... ;.;,,,,,.,.;;,,,,,, . ;.:,..~ ........ ;:.-:.~ ........ ;;~;,;;~ .. ; ......; ... :; ....... ~.:;.~ ..:;.'..~.,;:.~;;;,.;;i~~:];;;:~~.... ;;;,:,,
..... ..
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~())
-
,
:.. ,, ... ,... ,,.,:.~,,;:,,;:~.-:::~;.::."::"'''.'"'.".'''':~.:::::::. .. :.:.. :.'.''.'.''''"~':::::".:;:~~"'"'''''.'''""'"'"''~~"'"'''"~''t''''''"'''''''''.''"''''.:;"''''''''"''''.'' ., ...... " .. ,,, .. ,",:
. . . . . . . . . . . . . . . . ,..............................................................................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).
PyQt
, ,
ui-
pyuic4.bat.
. ,
, .
Qt
" .
Designe. "
19.
19.6.
377
PyQt
PyQt
PyQt
, PyQt4:
QtCore- , .
;
QtGui- , , , , , .;
PyQt4 QtDeclarative,
QtDesigner.
~ :
< >
QtCore QtGui:
19.7.
PyQt
++. , ,
. ++,
Python
, . .
.
, :
QString- Unicode-cpoa. ! 2 ( )
str . , !
\.
sip, setapi () :
378
>>> 5
>>> 5
11.
= QtCore.QString("cpoa")
PyQt4.QtCore.QString('cpoa')
> 5tr(5)
''
1.
API
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 (). ,
. :
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
.
. ,
.
380
11.
:-"'' .......... ~ ........ ~ ...~ ...... ' ................ ~~ ~' .....~. ......... , ......... ~ ............... , , .... ~~ ~~ .. '"~':'""~ ~: '.' '''.''~,~ '.< ::.
[ .19.12:nitlt ;rt:!n~:oilb.:4>n&pait .
;,.~
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!
?.~ ;.......... '... ;, .. ~ .. :;, :... '' .. :.; .: ......... ,;; . ,;, .~:.': ..'.'. :. ,;, ;.::... ;, .,~.:. : , ;:;:.=; ;:, :
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- (
).
priority ().
started (), -
finished (). ,
u . ,
True,
isFinished ()
True,
u n
. , - GUI-,
, . GUI-
.
emit ()
. , n
, .
- GUI-.
QThread (
19.14).
(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
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.
. ,
setDisaed ().
n finished ( J .
, n
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.
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.
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.
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.
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])
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;
. ,
False)
+
+
n, n .
task _ done ( 1 - n. n ;
390
qsize () n
/1.
n .
n,
+
+
empty ()
full () -
True,
n,
True,
False-
n ;
False-
n (
19.17).
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()
QPushButton ( ), QWidget.
QWidget, ,
, . ,
QPushButton.
MyWindow setext ()
. Queue queue.
,
. (
) .
taskDone ( int,
.
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 ()
lock ();
unlock () - .
QMutex (
19.18).
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
Myhread
''~"!'.'.,...'.'''''"
''" '''""" ''''""' <""",,.,., '''"''"" ' " .. "'''"'~" ''"'' "''''''' ,>> ~ ..,, ~ ... ,"''''"'."'''''''""~-~''~'~ ... , "'''~""~~~ ..... ~'"" >>><~ ''' '' '" ''" '+-"' '''' '" "''" ~'" "
">
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
),
). 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~~,,:
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
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 .
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- . ,
False-
20.2.
QWidget ,
: , , .
setWindowFlags () flags
QWidget. , setWindowFlags ()
. :
setWindowFlags(<Tn
>)
+
+
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))
. 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 (<>)
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, ;
minimumSizeint
() -
QSize,
.
, , ;
rect () -
QRect,
, . :
20.
+ geometry () -
403
QRect,
n. :
+ ;
+ n .
n,
n .
;
+ n n ,
n n. 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
:
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.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 .
... ' ..... ' ... '' ... ' .... ' .... '..
.... ;
")
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
~ .......... ",,,,.,,,;,,,.,;,, .. ,,,,,,_,,,,,,.,,,,.,\,.,,,. .. ", .. .,,.,,.,,;,.,;;',;,,;;... ,,;,.,,, .... , .... ;.,.,,, .. ,~ .. ,,"''"''"''''';''",.""'""'"'""""""'"''''''"""'''''''"''"''"''"'"'"""""'""''"';,;.,,.,,.,.;,.,.,.,, ..,.,,,.,,,.,,,.",,,,,,,;.,,.,.,,.,,
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-
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 :
+
+
+
()
() -
setx (<>)
isNull () -
setY (<>)
- ;
True,
False-
>>> = QtCore.QPoint()
> . isNull ()
True
>>> p.setX(10); p.setY(88)
> .(), .()
(10, 88)
manhattanLength ()
- :
QPoint
n n
+,
+=,-(),-=,=
!=.
. n n -. ,
n
*, *=, 1 /=).
QPoint
(n
408
11.
20.5.2.
QSize
QSize.
QtCore
:
<~>
QSize()
<~>
QSiz(<>,
<~>
'Qsize (<QSize>)
<>)
.
. :
+
+
width ()
height () -
setWidtl)(<pa>)
setHeight (<>)- :
>>> s = QtCore.QSize()
>>> s.setWidth(10); s.setHeight(55)
>>> s.width(), s.height()
(10, 55)
+
+
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.
boundedo ( <QSize>)
QSize,
t expandedTo(<QSize>)
QSize,
t transpose () .
410
11.
(n*,*=,
/=). :
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. :
-1, -1,
0)
20.
411
>>> QtCore.QRect(r)
PyQt4.QtCore.QRect(10, 15, 400, 300)
:
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)
setSize(<QSize>)
setRect
(<1>,
<1>,
<>,
<>) -
>>> 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>),
(<1>)
moveTop (<1>) -
412
11.
+
+
+
+
+
moveRight
(<2>) moveottom(<Y2>)
moveTopLeft (<QPoint>) -
moveTopRight (<QPoint>) -
moveBottomLeft (<QPoint>)~oveBottomRight
. :
(<QPoint>) -
+
+
movecenter (<QPoint>) -
tr'ans1ate(<C >,
< >)
trans1ate(<QPoint>)-
trans1ated (< >, < >) trans1ated ( <QPoint>) trans1ate (), QRect,
adjust (<1>,
<1>,
<2>,
<2>)
:.
adjusted ( <1>,
<1>,
<2>,
<2>)
QRect,
+
+
+
1eft () () top () () -
;
;
right () bottom () -
;
+
+
width ()
height () -
size () - QSize. :
>>> r = QtCore.QRect(10, 15, 400, 300)
20.
413
+ 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 ()
. :
isNull ()
- rue, ,
Fa1se-
isVa1id () -
True,
1eft ()
< right ()
Fa1se-
Fa1se-
top ()
isErnpty () -
True,
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.
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
intersect (<QRect>)
intersected ( <QRect>) -
. :
unite(<QRect>)
united(<QRect>)
- ,
.:
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)
:
True, , False-
isFullScreen () -
isActi vewindow () -
rue, , False-
windowstate () -
, .
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.
")
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. :
PGM PNG
, ,
setWindowicon ()
Qicon.
QApplication.
.
:
QStyle
PNG
16
16
, n
20.7).
l:~:~~i~:~~:i?:?.~:~i.~~:~~~:~~:~~-~~~~~~:~~::~~~~::::::.:::.:~:.:::.::
. :. : .: : .: : :. : :. : .: : : : : : .: : : : : : : .: .:.: .: : : : . : : . : .
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([<>,
]<>,
<>)
<> . ,
QPalette.
<> .
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 (, 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
n n . n
n. ( n
n),
background-image)
SS-
20.9).
")
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 (
~:
;.,,;,~;;,
...;;;...
,;~.;
20.1 0).
....;.......:
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 ).
: :.:.: ::.=:; ::=.: .= : ....;,;;;,;;,,,;,,,;,,,:;;.;,=,;;;, ...... :.:.: : .. ;,,;,;,,;,;,=,;,,;;,;:;~ i:.:::::::. :: ... ;,;;,,;;........ ;;;,,,,,;... :.......
=. ,
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 () ( ). ;
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~()
.:. . ...... .. :...... ......... .... "; .. ............ :..:.'.. ............ ...........::. :............. . ..:: ..:. :.. .....:......:.
.......... ,; . :;.:. .. .. .. .. .:: ......... ...................................... :.... ........ .. ..... ....
~.'"
~:'.:
'
'." .~
:~.
"'
;;, ~.: ~;
on_clicked () ")
class MyClass():
def
init (self, =):
self.x =
def
call (self) :
rint("
MyClass.
call
()")
MyClass.on_clicked()")
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
,,
= 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)
CJUi t i
connect 1) n n ~1 .
n n (
21.3).
..... . . ........ ........... .............. ........................... ... ... ............ ....... .. .............. ............................... ... ... .... .................................... .............. ....................................................
~;,;;.~i-':iJ~~~;:n~-~~~:.~:.:,~~t~~:~..~:~.:
~~)g:.::>::;:: ":/
_,
:
........................... :.;;... ;.:::... :.... :.... ;.. :.....:;.: ...=
......... ;;,; . :~.. ,;;,=~.; ..;;,; .............~;;........ ;......... ;,;;,,,,-;;i,:::... : ....... ;.:; ....... : ........;;; ................. :.= ......................................................................:............. J
,.
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 ():
<ConnectionType>
.
, . . GUI- .
AutoConnection-
- .
QtCore.Qt:
DirectConnection,
QueuedConnection;
DirectConnection- 1 - .
;
430
11.
QueuedConnection- 2 - .
;
, . ,
;
UniqueConnection- - AutoConnection,
. ,
button2
, :
st
True
False
Autocornpatconnection- 3 - Qt 3.
21.2.
QObject:
ockSignals (<>) - ,
rue, , False.
;
signalsBlocked () - True, ,
False- ;
disconnect () - .
. :
disconnect(<Oe>,
disconnect(<Oel>,
<>,
<>,
<>)
<2>,
<>)
, .
, disconnect () True. , 11
. disconnect (), , ~1
. , :
21.
431
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
.
. . . . . . . . .
~: ;;;:~.; . . ~.';. . . .;. . ::. . . . .: ; ; , " ;,; ~ ;;; ; ;~;:,, : . . : : . :. " ~; .. ,; . . ; :~;, ,',, . . . ;;, i~.~.;; ~--...:,, ...... ". ,,... ,............................ ;................. "'" ........ 1 . . . . . . . . ' 1 " \ ... ' . . . " ' . ' . . . . . . . . . . "
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 ().
>
( [
) ")
n n n
n. , n .
n n (
21.5). n
clicked () ( n).
n n .
, , n n.
.
.......................................... :..........~ ......~ ....; :........ ~ ~.... ~.;: ;........ : ; : ;.;,,; ....... ; .;.:.....~.= ..... :......~ ;:.:::.::~ ;;.~ ...:;:;,,;~:;.:~;.;,:.:;,;;,.~.:.; :;,,;,,;,,:. ;:-...........~ ..........................................:
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 (int, int) "), 10, . 20)
PyQt_PyObject.
. ..,
:
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])
n :
436
n n, n
n .
11.
types
. , n n
int 11 str:
nae="mysignal")
n n n .
n . n n ,
n . .
n n n.
21.6).
n (
n n n.
,~
;. ;'. ~ ' : ; : :.. '; :=.; :} ,,; :. :. i.; .... :; ... ;.............. :......,:, :;; ... ;:. ::......:... :... ,;; ........ ;... :........... ;,.., ... ............ ....... '.. .. ................... . ................ ' .... ' ' ....... .. i
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")
21.
437
self.button2.clicked["bool"] .disconnect(
self.on clicked_button2)
self.mysignal[int] .disconnect()
self.mysignal[str] .disconnect()
self.button.setEnaled(False)
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
types
. n n n .
n . n
name ,
. n result n
n , . n ,
. n ,
n n . n
@pyqtSlot 1) n 21.7.
1...
..
..
..
(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.
21.5.
connect () .
- ,
,
. :
lmd-, .
10:
QtCore.SIGNAL("clicked()"),
: self.on_clicked_button1(10))
self.connect(s~lf.button1,
lamda
,
lmd-,
lmd- , . :
=
10
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.
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))
:
button1 10 False
21.6.
11
<Id> =
QObject.
tirnerEvent
().
startTirner ()
<>.strtimr(<>)
startTirner () ,
. <> , l.:
tirnerEvent(self,
<
QTirnerEvent>)
tirnerEvent ()
tirnerid () QTirnerEvent. :
<Id>
=<
QTirnerEvent>.tirnerid()
. <
> ,
.
,
QObject.
~t
killTlrner () 11
<Oe>.killTirner(<Id>)
11,
startTirner ().
,
,
21.8).
21.8.
Q .~:.10 .
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)
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
+
+
+
interva1 ()
- ;
timerid () - -1;
isSing1eShot () True,
Fa1se- ;
isActive () -
True,
Fa1se-
1 QTimer scartTimer ()
killTimer()
(21.9) .
............,.........................................,....,.......................,., ..........................................................................................................................
"
1 ' ' " . ' . ' ' : . ' : ' 1 . . . . . . . . . . . . . : , ; ' " ; . . . . . . : : . . . . : .....
. . . .
~-. '
" : : . ;: 1 "
. . . . . . . . . . . . . ' , ; ' 1
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 -
ignore ( 1);
registerEventType ( [<> J 1 -
. .
( 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-
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,
. n iI, n,
MouseButtonPress n
QMouseEvent,
11
KeyPress- n QKeyEvent. ,
.
n . True, n n
. n n ,
event
r) n . :
return QtGui.QWidget.event(se1f,
QWidget n
. n, n QLabe1 :
return QtGui.QLabe1.event(se1f,
n , 11I
21.10.
init
(self, parent=None):
QtGui.QWidget.
init
(self, parent)
se1f.resize(300, 100)
def event(se1f,
):
if e.type() == QtCore.QEvent.KeyPress:
print
("
")
445
21.
'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>
<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
::............ :....... ::; .. .... :.......:...... ..... :.:: ........ :..... :................. ::::............. ......:"'": ........
,
:~.:
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.
pos 1)
oldPos 1)
QPoint
fl;
QPoint
size 1)
oldSize 1)
QSize
- n
QSize
n J.
21.12 .
...............
447
21.
QtGui.QWidget.
self.resize(OO,
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.
<>,
<>)
, -
<event>
close ()
ignore ()
accept ().
Yes,
No
21.13).
, .
:''''''."'''''~
[.:.~:~~~-~-~--~~.:~.~.: . 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- - ;
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,
15
1349
450
11.
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 ;
+
+
focusPo1icy () - ;
grabKeyboard () -
. n -
re1easeKeyboard ();
re1easeKeyboard () - .
, ,
focusWidget () QApp1ication. n ,
None.
QWidget.
n :
+
+
<event> n QFocusEvent,
:
gotFocus () -
1ostFocus () -
reason () -
. -
<>
setFocus ().
21.14).
n , n
n. ,
<>.
21.
451
. ...... i
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>
. ,
, .
,
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
( <ID> [,
<> J)
<>
True ( ),
<ID> . False .
QEvent. Shortcut,
+
+
shortcutld () - ' ;
isAmiguous
() -
+ key ()
1 rue,
False-
QKeySequence.
, (
21.1 5).
(<Ait>+<E>)-
(<Ait>+<Y>)
(<Ait>+<B>)
grabShortcut ().
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 :
<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>:
isAutoRepeat () -
rue, n
False- n ;
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;
<Shift.>+<Tab>.
<>
, accept () .
,
21.10.
accept ()
ignore ( J.
, .
,
I, .
, ,
.
, .
21.1 0.1.
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 -
, .
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 ().
mouseoveEvent () ,
- n . ,
21.
457
.
,
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>,
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, - ""
. :
0))
QCursor :
pos () -
QPoint
. :
print(QtGui.QCursor.pos()
.(),
QtGui.QCursor.pos()
.())
setPos () . :
setPos ( <>, <>) set Pos ( <QPoint>).
460
21.11.
11.
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
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
pixmap () - n QPixmap , n
;
. napal\.1epa n
drag.setHotSpot(QtCore.QPoint(20, 20))
hotSpot () -
QPoint
""
n ;
drag.setDragCursor(QtGui.QPixmap("cursor.png"),
QtCore.Qt.MoveAction)
+
+
source ()
- n-;
target () -
n-n
None,
n-
n.
+
+
QDrag
n :
- 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):
text/plain).
dt.stt(" ")
+
+
True, ~
1
!
setHtml (<L->) -
text/html). :
HTML (I-
dt.sttml("<> L-</>")
+
+
html () -
hasHtml 1)
HTML
(I- text/html);
HTML (I-
True,
text/html), False- ;
urls 1) -
~ URI-apeca:
uri
hasUrls 1) -
True, URI-apeco
setimageData (<
>)
(I-
application/x-qt-image). ,- ,
Qimage QPixmap. :
data. setimageData (QtGui .Qimage ( "pixmap.png"))
data. set ImageData (QtGui. QPixmap ( "pixmap. png") )
imageData () -
, setimageData () );
+
+
<>) -
I-. I- , -
21.
463
QByteArray .
I-. :
("",
"utf-8")))
data(<MIME-n>)-
QByteArray ,
I-;
True,
False- ;
+.
forinats () - I-;
removeFormat ( <I->) - , 1 -;
clear()- I-.
- ,
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,
<event>
QDragLeaveEvent;
<event>) -
. <~vent> QDragEnterEvent;
dragMoveEvent (self,
<event>)-
<event> QDragMoveEvent;
464
/1.
QDragLeaveEvent QEvent
. , .
:
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 () -
, .
. ,
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.
. n , n
(w ) . t!
clipboard () QApplication:
clipboard
QtGui .QApplication.clipboard ()
QClipboard ( ;
n QClipboard):
+ text ( [<>] ) - ;
+ text (<> [, <>]) - .
, - . <>
. QMimeData.
+
+
(. .
21. 11.2);
<> Clipboard (
no
dataChanged ().
21.1 3.
, .
, QObject,
eventFilter (self,
<>,
<event>). <>
, <event>- .
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>) -
<QObject> , ,
<QEvent>- . n
(, QMouseEvent), n n
, QEvent. n
QEvent .MouseButtonPress label:
= QtGui.QouseEvent(QtCore.QEvent.MouseButtonPress,
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:
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 ).
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
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 .
. 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-
QWidget
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.
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])
,
,
. < >
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 (<>,
< >) -
<>;
<>;
+
+
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
. :
n n. n
, setLayout ()
n.
474
QFormLayout
11.
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 .
. :
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 , ,
. :
QStackedLayout. , QStackedWidget
:
22.
indexOf (<r>) -
477
_len _
r) -
len (), .
currentChanged ( int)
22.6.
widgetRemoved ( int).
QSizePolicy
, ,
,
sizeHint ().
QSizePolicy.
setSizePolicy ( <QSizePolicy>) QWidget,
sizePolicy () .
QSizePolicy :
>[,
< >]])
, ,
sizeHint ().
QSizePolicy:
Fixed- ,
sizeHint ();
QSizePolicy
>)
>)
setVerticalStretch(<aop
setHorizontalStretch(<aop
>)
>)
478
11.
, ,
.
.
, .
rue
setHeightForWidth (<>). ,
heightForWidth (<>) .
22.7.
, .
. ,
. QGroupox.
:
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;
11 11 n
1. n
AlignHCenter AlignRight. :
box.setAlignment(QtCore . Qt . Al ignRi ght i
Ecm1
True, n
, n ,
, n nn 11.
;
"'
:J QGrotrp8ox
isCheckale () -
ralse -
+
+
rue, n,
n ;
1t rue, ,
, , ~~
22.2. QGroupBox
ra l se -
ralse-
True,
QGroupox :
n ,
True,
. ra l s e - :
t toggl ed (bool) -
np~1 1111 ,
n. 111 n rue.
. false- .
22.8.
1 . n,
n . t .
:
480
<~>
QFrame
parent
[,
flags=<T >])
QFrame([parent=<Poe>]
11.
None,
, . , ,
flags
, . , ,
, , .
flags,
20.2.
( ;
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 :
QaWi~get
QaWidget :
<>= QWidgt([<>))
< > n.
, n . n n
QabWidget :
1" ) ,
2" ),
3"),
" ..n
"
"
&1")
&2")
&3")
vbox . addWidget{ta
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,
setUsesScrollButtons (<>) -
True,
. , ,
,
. False ;
<>)
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 .
, .
:
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
i temext (<>) - ;
setitemicon(<ec>,
<Qicon>)-
.
Qicon;
False,
:> .
True ;
count () -
False-
len ():
print(toolBox.count(), len(toolBox))
currentindex () - ;
currentWidget () -
widget (<>) - ,
,
None;
indexOf (<>) - ,
<>. , -1;
setCurrentindex (int) -
setCurrentWidget (QWidget *) - ,
. .
currentChanged ( int).
.
22.11.
QSplitter ,
. :
QSplitter([parent=<Poe>])
<>
QSplitter(<Opea>[,
rnt=<>])
parent .
None, .
<> .
486
11.
, .
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;
savestate () -
QByteArray .
(n, ), n
restoreState(<QByteArray>);
, n;
setCollapsie (<>,
<>) -
Fa1se n <> n
n ;
n . n n
n ;
setStretchFactor (<>,
<>) -
setSizes (<>) -
n n,
- n n;
sizes () - ( ). :
print(sp1itter.sizes())
#:
[308, 15]
22.
count () -
487
len ():
widget (<>) -
indexof (<n>) -
None;
<n>. , -1.
splitteroved(int,int).
:r : , -
.
22.12.
QScrollArea .
, .
. :
- QScrollArea
QScrollArea :
<>= QScrollArea([<Poe>])
QScrollArea ( ;
):
setWidget ( <>1 - ;
False
setAlignrnent (<>) -
. :
scrollArea.setAlignrnent(QtCore.Qt.AlignCenter)
ensureVisie (<>,
(<>,
<>) 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 - ;
i . ~.
23
QWidget.
QObject
, t ,
, . ,
, ., .
,
. .
,
.
23.1.
,
,
, . ,
HTML,
QLabel.
PyQt
CSS,
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>. :
")
&, n ,
n. , n &, n
, n n.
<Ait>
n,
setBuddy (), .
&, .
n n, & .
:
setNum(<co>)- n 9
n.
setWordwrap (<>) -
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)
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.
+ setPicture (<QPicture>) -
QPicture&) ;
+ setovie (<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
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. :
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>) - .
:
+
+
seticon (<Qicon>) - ;
seticonSize (<QSize>) - .
QSize. seticonSize (const QSize&);
23.
493
animateClick ( [<> J) -
. .
,
100 .
click () - . ;
toggle () -
. ;
setCheckae (<>) -
True,
, -
;
setChecked (<>) -
True,
setChecked (bool);
setDown (<>) -
rue,
isDown () False -
True, ,
True,
().
False- .
QAstractButton :
+
+
+
pressed () released () -
;
;
clicked(bool=O)- ,
. ;
toggled (l;_ol) -
. -
QPushButton (
; ):
<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 () -
;
;
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
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.
+
+
+
+
isReadOnly () True,
False- ;
setAlignment
(<>) - ;
setaxLength (<>) - ;
setDragEnaed (<>)
True,
.
;
setPlaceholderText (<>) -
, ;
setText (<>) - . :r
(const QString&);
setext
insert (<>) - .
, ;
+
+
text () -
, ;
displayext
() -
, .
setEchoMode (), ,
Password *;
+
+
+
selectedText () - ;
clear () - . ;
backspace () - . ,
, ;
del_ () - . ,
, ;
setSelection(<ec>,
<II>)- <>,
<>. ;
+
+
selectAll () - . ;
~electionStart ()
+
+
+
+
+
-1,
- ;
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 :
edi tingFinished () -
<Enter>
+
+
+
returnPressed () -
<Enter>;
selectionChanged () - ;
textChanged (const QString&) -
.
;
498
11.
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:
+ QDou1eVa1idator-
. :
QDou1eVa1idator([parent=None])
QDou1eVa1idator(<Haaoe
<
>,
<
>,
>,
<>)
, .
100. .
1ineEdit.setVa1idator(
QtGui.QDouleVa1idator(O.O,
100.0, 2, window))
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.
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 (<>) -
. , . ~
append (<>)
- HT~L -
+
+
+
- (
- (
<ti tle> );
<title>);
- , ;
23.
501
+ toHtml () - HTML;
+ clear () - . ;
+ selectAll () - . ;
+ zoomin ( [range=l)) - . ;
+ zoomOut ( [range=l]) - . ;
+ cut () - ,
, . ;
() -
, ,
. ;
paste () -
, . ;
canPaste () -
True, , False-
acceptRic?Text () -
HTML,
True,
False- ;
undo () - , ,
. ;
redo () -
. ;
isUndoRedoEnaed
'
() -
False- ;
True,
False- ;
createStandardContextMenu ( [ <QPoint> J ) -
.
, , QTextEdit,
contextMenuEvent (self, <event>).
ensureCursorVisie
() -
) . ,
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;
, ;
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
+
+
fontFamily () - ;
setFontPointSize (<>) - .
setFontPointSize (qreal);
+
+
fontpointSize () - ;
setFontWeight (<>) - .
setFontWeight (int);
+
+
fontWeight () -
setFontitalic(<a>)- n True,
.
fontitalic () -
setFontitalic (bool);
True, , False- n
fontunderline () -
True, n, False- n
setextColor ( <QColor>) - .
,+
+
0) .).
textColor () - n QCo1or ;
setTextBackgroundColor (<QColor>) - .
QtCore.Qt (n, k, white . .) n "
23.
505
+ textBackgroundColor () - QColor ;
+ setAlignrnent (<>) -
. .
22.2.
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 () -
. ;
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 () .
:
<> , ~ <QRegExp>
.
,
position
<QextCursor>.
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,
;
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
QTextBlock,
QTextDocument :
undoAvailae
(bool) -
. n True,
n ,
redoAvailae
(bool) -
False-
n . rue,
n n ,
False-
n .
undoCommandAdded ( ) -
;
ockCountChanged
( int) -
cursorPositionChanged(const
QextCursor&)-
- . , n
n ;
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>) -
, .
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 () -
;
+
+
insertHtml (<>) -
HTML.
23.
511
no
23.7.
QTextBrowser QTextEdit
n
no
n n .
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 :
URL-apec ;
backwardAvailae (bool) -
. ;
forwardAvailae (bool) -
. ;
highlighted(const QUrl&)-
. URL-apec
( QUrl) ;
+
+
historyChanged () - ;
sourceChanged(const QUrl&)- .
URL-apec .
QtWebKit,
QTextBrowser
23.8.
JavaScript.
QSpinBox (
QDouleSpinBox ( ). ,
. :
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,
;
stepDown () - . ;
stepUp () - . ;
st(<>)- ( )
(n ) ;
'text () -
., ;
clear () - . ;
selectAll () - . .
<Enter>.
QSpinBox QDouleSpinBox (
; ):
setValue (<>) .
setValue (int) setValue (doule);
value () - , ;
cleanext () - ;
setRange (<>,
setPrefix (<>) - , n
;
setSuffix (<>) - ,
;
setSingleStep (<>) - , n
.
17
1349
514
23.9.
11.
QDateimeEdit (
),
QDateEdit
( )
QTirneEdit
( ).
, .
. :
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
irne ( ) .
(r ;
r ):
setDateTirne(<QDateTime>)- .
QDateTirne datetirne Pytln.
setDateTirne (const QDateTirne&);
.
t
setDate (<QDate>) - .
QDate date Python.
setDate (const QDate&);
setirne(<Qirne>)- .
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 .
setTimeSpec (<>) - .
LocalTime, u OffsetFromUTC QtCore.Qt;
setCalendarPopup (<>) -
True,
setSelectedSection (<>) -
+
+
+
+
+
+
+
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
. :
QCa1endarWidget:
<>= QCa1endarWidget([parent=<Poe>])
QCa1endarWidget (
; ):
setSe1ectedDate (<QDate>) - .
QDate date
+
+
Python.
se1ectedDate () - QDate ;
setDateRange (<>, <>), setMinirnumDate (<>) setMaximumDate
(<>) .
QDate date
Python;
setCurrentPage(int,int);
+
+
+
monthShown () - ( 1 12), ;
yearShown () - , ;
showSe1ectedDate () -
. ;
showoday () -
. ;
showPreviousMonth () -
. t
. ;
showNextMonth () -
. n
. ;
showPreviousYear () -
. ;
showNextYear () - .
. ;
setFirstDayOfWeek (<>) - .
. ,
Monday QtCore. Qt;
setNavigationBarVisile(boo1);
setHorizonta1HeaderFonnat (<>) -
QCa1endarWidget:
23.
517
NoHorizontalHeader- - ;
SingleLetterDayNarnes- 1 -
;
ShortDayNarnes- 2 - ;
LongDayNarnes- 3 - ;
setVertica1HeaderFormat (<>) - .
QCalendarWidget:
NoVerticalHeader- - ;
rsoweekNumers- 1 - ;
;
setSelectionode (<>)
QCalendarWidget:
NoSelection- - ;
SingleSelection- 1 - ;
setHeaderTextFormat (<QTextCharFormat>) - .
QextCharFormat;
setWeekdayextFormat (<
>,
<QextCharFormat>)-
. Monday, uesday,
setDateTextFormat (<QDate>,
<QTextCharFormat>) -
QtCore .Qt,
. QDate
activated(const QDate&)-
<t>. ;
clicked(const QDate&)- .
;
, - ;
selectionChanged () -
23.11.
QLCDNumer . ,
, .
, ,
. :
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 ,
.
:
23.
519
QProgressar:
<>= QProgressBar([parent=<Poe>])
QProgressBar ( ;
):
value () - ;
text () - , ;
setRange (<>,
setMaxirnum (<>) -
. ,
,
.
setMaxirnum(int);
reset () - . ;
setTextDirection (<n>) -
. ,
.
QProgressBar:
t torn- -
90
ottornToTop- 1 -
90
valueChanged ( int) .
23.13.
QSlider ,
. :
QAstractSlider
- QSlider
QSlider:
<>= QSlider([parent=<Poe>])
<>= QSlidr(<>[,
rnt=<>])
<> .
11.
520
QSlider QAstractSlider (
; ):
stVlu(<>)-- . ~
setValue (int);
+
.+
+
value () -- ;
setSliderPosition (<>) -- ;
sliderPosition () -- .
( ),
,
,
value ()
sliderPosition ()
value ().
,
--, ;
setRange (<> 1
<>)
setOrientation (<>) -- .
Horizontal Vertical QtCore.Qt;
setSingleStep (<>) -- ,
;
setPageStep (<>) -- ,
<Page Up>
<Page Down>,
<Page Up>
<Page Down>,
setracking(<a>)-- True,
( ).
valueChanged(int) .
False, valueChanged ( int)
;
hasracking () -- rue,
,
False--
QAstractSlider :
<Page Up>.
, SliderNoAction (),
SliderSingleStepAdd
(1),
SliderSingleStepSu
(2),
SliderPageStepAdd
(3),
SliderPageStepSu ( 4), SliderToMinimurn (5), SliderToMaximurn ( 6) SliderMove (7)
QAstractSlider;
t
t
23.
521
sliderPressed () - ;
slideroved ( int) -
sliderReleased () - ;
valueChanged (int) -
QSlider ( ;
):
NoTicks -
,icksBothSides- ;
TicksAove- ;
TicksBelow-
TicksLeft
TicksRight-
. ;
- ;
;
setTickinterval (<>) - 11 .
23.14.
QDial
QDial 1 (
),
. ,
- . :
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 . :
QAstractSlider
- QScrollBar
QScrollBar:
<>= QScrollBar([parent=<Poe>])
<>= QSrllr(<>[,
rnt=<>])
<> n n n.
Horizontal Vertical ( )
QtCore.Qt.
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 . :
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 (<>,
<>) - ;
- ;
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.
<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
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 (),
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 :
24.2.
QFontComoBox n .
, n
, . :
QComoBox
QFontComoBox
527
24.
QFontComoBox:
<>= QFontComoBox([parent=<Poe>])
QFontComoBox QComoBox (. .
24.1)
+ setCurrentFont (<QFont>) -
.
m.
currentFont () QFont .
:
print(comoBo~.currentFont()
QFont.
.family())
setFontFilters (<>)- .
QFontComoBox:
AllFonts -
ScalaeFonts
NonScalaeFonts- 2 -
MonospacedFonts- 4 -
ProportionalFonts- 8 - .
1-
;
;
QFontComoBox
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.
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>])
rnt=<>])
QStringListModel (
; ):
+
+
+
- , ;
(<>,
<>
removeRows (<>,
<>
[, parent] ) -
[,
True,
parent]) -
, , .
rue, ;
data
(<Qodellndex>,
<>)
+
+
rowCount ( [parent])
sort
(<
<QModellndex>;
- ;
>[,
order=AscendingOrder])-
AscendingOrder QtCore.Qt,
,
DescendingOrder- .
( 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 (
; ):
+
+
+
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>) - .
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, ;
+
+
QStandarditem);
takeColumn (<>) - ; (
QStandarditem);
clear () - ;
532
item(<Cpoa>[,
+
+
<>=])- (
invisileRootitem ()
QStandarditem),
11.
-
QStandarditem);
itemFromindex (<QModelindex>)
QStandardrtem), <QModelindex>;
index (<>,
(
<>
[, parent=QModelindex () ] ) -
QModelindex), ;
indexFromitem(<QStandarditem>)
QModelindex), ;
rue, ;
+
+
- ,
<QModelindex>;
setHorizontalHeaderLabels (<
>)
setVerticalHeaderLabels (<
>) - .
setHorizontalHeaderitem(<ec>,
<QStandarditem>) -
QStandarditem;
QStandarditem;
l(
+
+
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
order=AscendingOrder] ) .
AscendingOrder QtCore.Qt,
, DescendingOrder- ;
+
+
QModelindex) -;
hasChildren ( [parent=QModelindex () ] ) -
True,
E'alse-
, ,
.
QStandarditem).
24.4.4. QStandardltem
QStandarditemodel
QStandarditem.
, )'.
:
<>
= QStandarditem()
<>
QStandarditem(<Tec>)
<>
= QStandarditem(<Qicon>,
<>
<>
<>)
QStandarditem(<Koeco >[,
< >=l])
= QStandarditem(<QStandarditem>)
QStandarditem ( . ;
):
+
+
+
+
+
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;
QStandarditem;
QStandardrtem;
insertColum(<ec
>,
<>)-
. <>
QStandarditem;
insertColUIIU1s (<>,
<>) -
+
+
removeRow (<>) - ;
removeRows (<>, <>) - .
, <>;
+
+
removeColUIIU1 (<>) - ;
removeColUIIU1s (<>, <>) - ,
, <>;
takeChild(<Cpoa>[,
<>=])-
( QStandarditem);
takeRow (<>) -
!:.J
( QStandarditem);
takeColUIIU1 (<>) -
( n QStandarditem);
parent ()
QStandarditem) None;
hasChildren () 1 True, ,
F'alse- ;
24.
535
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- ;
flags () - ;
setEditae(<a>)- rue,
;
setDropEnaed (<>) -
True,
setEnaed (<>) -
.
True,
False ;
536
+
+
11.
>
[,
order=AscendingOrder]) -
QtCore. Qt,
AscendingOrder
DescendingOrder-
24.5.
ListView- , . , ;
+
+
QaleView- <l{l ;
QTreeView- .
QComoBox
),
QaeWidget () QTreeWidget ( ).
"/", . n
.
24.5.1.
QAbstractltemView
QAstractitemView i!.
:
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 - ;
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 (<>) -
QAstractitemView:
NoDragDrop-
DragOnly- 1 - n
oropOnly- 2 ~n ;
oragorop- 3 - n n ;
Internalove-
n;
n;
4 -n , ;
set;DropindicatorShown (<>) -
True,
setAutoScrollMargin (<n>) -
n .
QAstractitemView :
activated(const Qodellndex&)- , ,
n <Eter>.
(n Qodellndex);
. n n (
Qodelindex);
. 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 .
:
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 (<>);
+
+
setSpacing (<>) - ;
setSelectionRectVisie (<>) -
True,
,
.
;
True,
, , . False
;
'
selectedlndexes () -
( Qodellndex) -
24.5.3.
QModellndex.
QTaleView . :
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(int);
, n
resizeRowsToContents () -
. ;
resizeColunmToContents
(<~ >) -
, n .
resizeColunmToContents(int);
resizeColunmsocontents () -
, n
. ;
setSpan(<e~<:c 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 -
- ;
;
;
, . .;
, . .;
ralse-
setShowGrid(bool);
rue,
.
;
False
setWordWrap(<a>)- True,
;
24.
24.5.4.
543
QTreeView . :
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,
+
+
True, , False -
setColumHidden (<>,
<>) - rue,
, , . False
;
hideColum (<>) -
hideColum
(int);
showColum(<ec>)- .
showeolum
isColumHidden (<>) ,
False -
( int);
True,
True,
<> <Qodellndex> ,
;
False -
544
isindexHidden ( <Qodelindex>) -
11.
True,
<>)
setExpanded (<QModelindex>,
rue, , n n
, , False- . n n
n Qodelindex;
expand ( <Qodelindex>)
n n
expandToDepth (<>) -
+
+
expandToDepth (int);
expandAll () - . ;
collapse (<QModelindex>) - ,
n n
Qodelindex.
+
+
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 ;
+
+
True,
n ;
selectedindexes () -
n (n- Qodelindex)
n n.
QTreeView :
n .
n n (n QModelindex)
;
collapsed(const
QModelindex&)- n .
n n (n QModelindex)
.
24.
24.5.5.
545
QHeaderView QTaeView
QreeView.
QTaeView
LJ
QAstractScrollArea
- QHeaderView
QHeaderView:
<>= QdrViw(<>[,
rnt=<>])
<> .
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 ;
+
+
+
Fa1se-
sectionsHidden () Fa1se-
True,
hiddenSectioncount () - ;
setDefau1tAlignrnent
(<>)
setHigh1ightSections (<>) -
True,
setC1ickae (<>) -
True,
. , ;
setMovae (<>) -
True,
isMovae
() -
Fa1se-
movesection(<Oya>,
True,
<>)- .
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> ,
<> <Qodelindex> ,
True,
false- n
rowintersectsSelection (<>,
<Qodelindex>)
True,
<> <Qodelindex> ,
false -
n ;
columnintersectsSelection(<ec>,
<Qodelindex>)-
True,
<> <Qodelindex>
,
false -
selectedindexes () -
n ;
n (n Qodelindex)
n n;
548
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(const
Qiteffiselection&,
QitemSelectionodel::
SelectionFlags);
setCurrentindex (<QModelindex>,
Qodelindex&,
<>) -
setCurrentindex (const
QitemSelectionodel::SelectionFlags);
currentindex () -
(n
Qodelindex) -
clearselection () - . .
QitemSelectionodel :
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-
;
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
,
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,
setFilterWildcard (<>) -
, :
? - ;
*-
[ J -
;
.
.
, .
setFilterKeyColumn(<ec>)- ,
. -1,
.
;
setFilterRole(<Po>)- (. .
24.3),
. DisplayRole;
setFilterCaseSensitivity(<Pe>)-
caseinsensitive QtCore.Qt,
, Casesensitive- .;
25
, ,
. ( ,
, , )
paintEvent () ( . .
21.8.3).
repaint () update ()
QWidget. paintEvent ()
QPainter.
QPainter ,
n, QPaintDevice.
QWidget QPaintDevice. QWidget
,
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",
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
, ,
) n :
+
+
name () - n "#RRGGBB";
setRgb(<!<:pac>,
<>,
<>[,
alpha=255])-
RGB.
255. n alpha n n
. n , 255- n
ri;
25.
553
t
t
255;
white = QtGuioQColor.fromRgba(4294967295)
t
t
t
t
rgb () rgba () - ;
setRgbF(<pac>,
<>,
<>[,
alpha=loO])- ,
RGB.
10 . alpha
. , 10 -
;
setAlphaF (<alpha>) -
10 ;
fromRgbF(<pac>,
whiteo= QtGuioQColorofromRgbF(1oO,
getRgbF () >,
10,
10,
10)
(<>,
<>,
<
<alpha>);
, , , "" ()) :
stmk(<>,
<>,
<>,
<>[,
alpha=255])-
.
255. alpha
554
11.
. , 255-
;
fromCmyk
(<>,
<>,
<>,
<>
[,
a1pha=255] ) -
QCo1or .
255. . :
white = QtGui.QCo1or.fromCmyk(0,
+
+
255)
getCmyk () :>,
<>,
<>,
(<>,
<
<a1pha>);
setCmykF(<oyo>,
<>,
<>,
<>[,
a1pha=1.0])-
.
. 1. . a1pha
. . , 1. -
;
fromCmykF(<oyo>,
<>,
<>,
<>[,
a1pha=1.0])-
QCo1or .
. 1. . . :
getCmykF () >,
(<>,
<>,
<>,
<
<a1pha>);
, ()) :
setHsv (<>,
<>,
<>
359,
white =
[,
a1pha=255 J ) -
255;
frmsv(<>,
HSV.
QtGui.QCo1or.fromsv(O,
255, 255)
getHsv () -
(<>,
>,
<>,
<
<a1pha>);
a1pha () -
setHsvF (<>,
<>,
HSV.
<> [,
a1pha=1. ] ) -
1.0;
fromsvF(<Oeo>,
<>,
<>[,
a1pha=1.0])-
QCo1or .
. 1. . . :
white =
QtGui.QCo1or.fromsvF(O.O,
25.
(<>,
getHsvF () >,
555
<>,
<
<alpha>);
alphaF () -
HSV
.
.
spec () -
,
()
Hsl ( 4);
. !'
spec ().
. :
toHsv ()
converto
toHsl (),
()
whiteHSV = QtGui.QColor.fromsv(O,
whiteRGB = whiteHSV.toRgb()
25.1.2.
QPen
QPen.
-. :
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 < >
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,
. :
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
>)
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
() ,
.
. :
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()
pointSize=-1] [, weight=-1]
[, italic=False])
<>=
QFont(<QFont>)
, !i
.
setFont ()
QApplication.
.
pointSize . weight
: 99 Light
(75)
Black
(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- ;
italic () ;
False-
rue, , Fa1se-
25.
561
n,
+ underline ()
True, n, False-
n ;
+ overline ()
False-
True, ,
n ;
strikeOut () -
True, n , .False-
n .
n n . n families ()
QFontDatabase. n . :
print(QtGui.QFontDatabase() .families())
n n n , n
styles
(< >)
QFontDatabase:
smoothSizes
(< >,
<>)
n~
QFontDatabase:
QFontMetrics:
<> n
, .
length
+
+
height () -
n :
QFontMetrics n .
QFontMetricsF.
562
25.2.
11.
QPainter
QPainter
QPaintDevice
QPaintDevice.
QWidget, QPicture, QPixmap, Qirnage, QPrinter
. , ,
. :
<>
<>=
QPainter()
QPainter(<QPaintDevice>)
, .
,
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 ().
, ,
.
>)
setBrush(<QBrush>)
setBrush(<C
>)
setpen () QPainter. :
setBrush () .
563
25.
,
. ,
.
, , , .
, QPainter (
;
QPainter):
+ drawPoint ()
- . :
drawPoint(<X>, <>)
drawPoint(<QPoint>)
drawPoint(<QPointF>)
+ drawPoints ()
- . :
drawLine () - . :
drawLine(<QLine>)
drawLine(<QLineF>)
drawLine(<QPoint>, <QPoint>)
drawLine(<QPointF>, <QPointF>)
drawLine(<X1>, <1>, <2>, <2>)
drawLines () -
. :
QLine>)
QLineF>)
drawPo1yline () -
, .
. :
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>)
. :
drawPo1ygon () - . i :
drawPo1ygon(<QPoint 1>[, ... , <QPoint N>])
drawPo1ygon(<QPointF 1>[, ... , <QPointF N>])
drawPo1ygon(<QPo1ygon>[, fi11Ru1e=OddEvenFi11])
drawPo1ygon(<QPo1ygonF>[, fi11Ru1e=OddEvenFi11])
drawEllipse ()
- . :
drawArc ()
rx-
rY-
- . :
drawArc(<X>,
<>,
<>,
<>,
< >,
<>)
16 * 360.
1/16
,
;
drawChord ()
. :
drawChord(<X>,
<>,
<>,
<>,
<~ >,
<>)
drawChord(<QRect>,
drawChord(<QRectF>,
drawPie () -
< >,
< >,
<>)
<>)
drawPie ()
. :
drawPie(<X>,
<>,
<>)
<>,
<>,
<~ >,
drawArc (),
25.
565
". , . 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 ().
<>,
<>)
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 ():
<2>,
<2>,
<2>)
<2>)
QPixrnap.
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.
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
(<>) ~
( ).
, - ;
. , .
, - ;
< >) -
. ,
painter. save ()
painter.restore()
#
#
#
save (),
restore ():
, . 1:1 .
,
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
drawPicture ( 1
QPainter.
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=" ")
:
NG
PGM PNG
, ,
for i in QtGui.QimageWriter.supportedimageFormats():
print(str(i, "ascii") .upper(), end=" ")
:
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 () -
False -
loadFromData ( <QBYteArray> [,
format=None] [,
f lags=AutoColor] ) -
n QByteArray. n ,
bytes. rue,
,
False
- ;
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.
.
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
. :
25.
573
:
<>
<>
<>
= QBitmap()
= QBitmap(<IIlpa>,
= QBitmap (<QSize>)
<>= QBitmap(<y
<>)
QBitmap(<QPi~~ap>)
<>=
QBitmap(<QBitmap>)
QBitmap
format=None])
>[,
<>
QPixmap
( ; ~
):
+ 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
-,
RGB
32 ;
32
-,
32
.
Qimage ( ;
):
True, , False-
isNull () -
ld(<
>[,
format=None])- .
.
(, "PNG"). ,
. rue,
,
False-
quality .
100. True, ,
False- ;
fill (<>) -
+
+
+
+
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
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
. n
availaeSizes
QPixmap;
( [mode=Normal] [, state=Off]) -
QSize) ;
25.
actualSize(<QSize>[,
577
mode=Nonal] [,
state=Off])-
( QSize) n , .
, , :
pixmap () -
( QPixmap),
, . :
im(<>,
.
:
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- .
~
,
) .
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 () -
;
). ,
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.
addRect () -
( QGraphicsRectitem). :
addPolygon () - ,
( QGraphicsPolygonrtem). :
addPolygon(<QPolygonF>[, pen=QPen()] [, brush=QBrush()])
addEllipse () -
( QGraphicsEllipsertem). :
addPixmap ( <QPixmap>) -
( QGraphicsPixmapitem);
addSimplee~t (<> [,
font=QFont () J )
QGraphicsSimpleTextrtem, (0, )
;
addText (<> [,
font=QFont () J) -
QGraphicsextitem,
(0,
0) ;
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.
n
,
26.1.4.
None.
n n QGraphicsScene~
itemAt () -
, n
None,
. :
, 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=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 ()
<>)
setSelected ()
26.
setSelectionArea(<QPainterPath>,
setSelectionArea(<QPainterPath>,
583
<Qransform>)
<>,
<Qransform>)
ContainsiternShape- - ,
;
IntersectsitemShape- l - ,
;
ContainsitemoundingRect-:- 2 - ,
;
IntersectsitemoundingRect- 3 - ,
;
+
+
selectionArea () - ( QPainterPath);
selecteditems () -
, ;
clearSelection () - . .
26.1.7.
QGraphicsscene
( ;
):
+
+
isActive () True, ,
False- ;
views () -
( QGraphicsView),
. ,
;
+
+
mouseGrabberrtem () - , ,
None, ;
render () -
. :
invalidate () -
. :
ItemLayer- l - ;
ackgroundLayer-
2 - ;
584
ForegroundLayer- 4 -
AllLayers- 65535-
11.
n n;
. n,
n n.
:
update () -
n n .
update(<X>,
<>,
<>,
<>)
update([rect=QRectF()J)
QGraphicsScene
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. :
- QGraphicsView
:
<>=
QGraphicsView([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)
). 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 () :
QPolygon
QPolygon
QPolygon
QPainterPath
QPointF.
maposcene
26.2.3.
<>)
() :
-> QPolygonF
-> QPolygonF
-> QPolygonF
->.QPainterPath
itemAt () -
None,
, . :
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:
.
, - ;
rotate(<Yo>)-
( ).
, - ;
shear (<
>,
<
>)
resetatrix
() - .
.
, .
,
QMatrix,
26.2.5.
setMatrix ().
matrix ().
QGraphicsView
( ; n
):
centeron () -
. :
centerOn(<X>, <>)
centerOn(<QPointF>)
centerOn(<QGraphicsitem>)
ensureVisile
() -
. :
ensureVisible(<X>,
<>,
<>,
<>[,
xargin=SO]
[,
yargin=SO])
fi.tinView () -
.
:
588
11.
render () -
. :
invalidateScene ( [ rect=QRectF () ] [,
layers=AllLayers] ) -
.
:
updateSceneRect (<QRectF>)-
updateSceneRect (n QRectf&);
updateScene (const
QList<QRectf>&).
26.3.
QGraphicsltem.
QGraphicsrtem .
QGraphicsScene).
QGraphicsitem , .
, QGraphicsitem
shape ().
26.3.1.
QPainterPath.
QGraphicsitem ( ;
):
setPos () -
). ~:
setPos(<X>, <>)
setPos(<QPointf>)
26.
+ pos ()
589
QPointF
( );
QPointF
scenePos () ;
sceneBoundingRect () -
QRectF, -
( ) , ;
+
+
+
setZValue (<Z>) - z.
.
.;
+
+
zValue () -
<
>)
z;
prepareGeometryChange () -
, ;
+
+
scene () None;
( QGraphicsScene)
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;
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
, - ;
<
>)
resetMatrix () - .
.
, .
,
, 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.
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 .
:
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 . :
596
11.
QGraphicsTextitem([parent=None] [, scene=None])
parent=None] [, scene=None])
<>=
<>= QGraphicsTextitem(<Tec>[,
n parent , n scene .
QGraphicsextitem
(n ; n n ):
+
+
+
+
+
+
+
+
n ;
font () - (n QFont);
setDefaul tTextColor (<QColor>) - no ;
setTextWidth (<>) - nn . n
, n ;
+
+
+
textWidth () - nn ;
document () - (n QTextDocument;
. .
(n
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 :
n n
no
n.
n n URL-apec;
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
+
+
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 () - . .
. rue,
, False- .
26.6.2.
QGraphicsDropShadowEffect : . :
QGraphicsDropShadowEffect([<QObject>])
QGraphicsDropShadowEffect
( ;
):
setColor(<QColor>)- . QColor(63,
63, 63, 180). setColor (const QColor&);
+
+
color () - ( QColor);
..
+
+
. ~
(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
. :
QGraphicsBlurEffect((<QObject>])
QGraphicsBlurEffect
( ; ):
t setBlurRadius (<>) t
lurRadius
. -
setBlurRadius (qreal);
()
- .
QGraphicsBlurEffect
blurRadiusChanged (qreal),
n .
.
26.6.4.
QGraphicsColorizeEffect
. :
QGraphicsColorizeEffect([<QObject>])
QGraphicsColorizeEffect
( ;
):
QColor (,
192,
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 ;
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;
, <>
<Shift>+<Tab>.
, accept ()
ignore ().
,
, :
focusinEvent (self,
<event>) -
<event> QFocusEvent (. .
focusOutEvent ( self,
<event>) -
21. 9. !);
<event>
QKeyEvent (.
21.9.3);
21.9.3).
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;
602
QGraphicsSceneMouseEvent
QEvent :
pos () -
11.
QGraphicsSceneEvent
QPointF
+
+
+
scenePos ()
screenPos () -
QPointF
QPoint ;
QPointF ~;~ -
lastPos () -
lastScenePos () -
QPointF
lastScreenPos () -
QPoint
buttonDownPos (<>) -
QPointF
+
+
+
button () -
, ;
buttons () modifiers () -
<A\t>
, ;
, -
(<Shift>, <Ctrl>,
.) .
,
. t ,
grabMouse () QGraphicsitein.
ungrabMouse (). ,
,
mouseGrabberitem()
QGraphicsScene.
,
, :
<event>
QGraphicsSceneHoverEvent;
+
+
<event>) -
<event>
QGraphicsSceneHoverEvent;
wheelEvent (self,
<event>) -
. ,
QGraphicsSceneWheelEvent.
<event>
26.
603
hoverEnterEvent (), hoverLeaveEvent () hoverMoveEvent ()
, .
+ 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
<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
:
, n n
. n <event> n n
QGraphicsSceneDragDropEvent;
dragMoveEvent (self,
<event>) -
n n
<event> n n
QGraphicsSceneDragDropEvent;
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 ();
, n n
26.
+ modifiers ()
<Ait>
+
+
605
, -
( <Shift>, <Ctrl>,
.) ;
buttons () - , ;
source () - None.
26.7.4.
,
.
sceneEvent (self,
<event>)
. <event>
. .
rue, , False- .
- ,
.
.
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 :
[,
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 (
):
def on_clicked():
dialog = MyDialog(window)
result = dialog.exec_()
if result == QtGui.QDialog.Accepted:
pr int (" n ")
# n
else:
print (" n Cancel")
accept () -
n :
self.btnOK.clicked.connect(self.accept)
reject () -
Cancel:
self.b~nCancel.clicked.connect(self.reject)
+
+
+
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- ;
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
();
20 . 1349
hide ()
setVisie
();
610
11.
, ,
finished ( int) -
hide ()
setVisile
().
setAutoDefault () True.
~ n
<Enter>,
n , .
n n <>.
setDefault () n
<Enter>,
no
. n
, .
27 .2.
QDia/ogButtonBox
QDialogButtonox ,
, , .
.
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
) 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 ( )
setStandardButtons (<
>) -
. :
se1f.box.setStandardButtons(QtGui.QDia1ogButtonBox.Ok
QtGui.QDia1ogButtonBox.Cance1)
addutton(<QAstractButton>,
<>)-
. ,
- . , . :
se1f .btnOK
se1f.box.addutton(se1f.btnOK,
QtGui.QDia1ogButtonBox.AcceptRo1e)
612
1/.
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 () - ;
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
27.
613
QMessageBox:
<>
QMessageBox([parent=None])
<>
Qssg(<>,
<
>,
<
>[,
buttons=NoButton] [ , parent=None] [,
flags=Dialog 1 MSWindowsFixedSizeDialogHint])
n
parent ,
, .
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;
+
+
+
+
+
Save
AcceptRole;
+
+
+
+
+
+
+
Abort
RejectRole;
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;
>) -
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
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;
, ,
, None,
;
buttonRole (<QAstractButton>)- .
, InvalidRole;
+
+
buttons () - , ;
removeButton(<QAstractButton>)- ,
.
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 :
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;
setComoBoxEditae (<>)
True,
setOption(<O>[,
on=True])- True,
False-
QinputDialog:
NoButtons- 1 - ;
UseListViewForComoBoxitems- 2 - JI
QListView,
QComoBox;
(.
QinputDialog :
. .
extinput;
.
extinput;
intValueChanged ( int) -
Intinput;
27.
intValueSelected ( int) -
621
.
Intinput;
douleValueChanged(doule)- .
.
Douleinput;
douleValueSelected (doule) -
.
Douleinput.
27 .4.2.
QinputDialog
, . JJ)I
getext
gtt(<>,
< >,
().
< >[,
None.
,
, .
mode
27.4.1). text
, n flags n .
getext () : (<>, <>).
(. setextEchoMode () .
n , - rue,
n ,
False, n Cancel,
<Esc>
n . :
" ",
" ",
tt=" ")
if ok:
print("Beeo
:",
s)
n .
27 .4.3.
27.5.
27.5.
JJ)I n getint ()
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,
" ",
" ",
("
:",
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,
"
" ",
",
print ("
:",
n)
27.4.5.
:
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)
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 -
Detai1 -
List -
;
;
1-
setFi1eMode (<>) -
r .
AnyFi1e-
ExistingFile-
Directory-
QFileDialog:
QFi1eDia1og:
, _ ;
1-
2-
ExistingFiles-
3-
<Ctrl>;
QFi1eDia1og ( ;
):
ShowDirsOn1y- .
Directory;
DcntConfirrnOverwrite- ,
;
27.
625
ReadOnly-
HideNameFilterDetails- ;
setOptions (<n>) -
setReadOnly(<a>)- True,
setNameFilterDetailsVisie (<>)
setDirectory () - . :
False, ;
setDirectory(<y>)
setDirectory(<QDir>)
+
+
QDir )' ;
directory () -
setNameFilter(<p>)- .
, . :
+
+
+
setHistory (<>)
- ;
. :
Lookrn-
FileName- 1 - ;
FileType -
Accept- - , (
- ;
2-
Open
Reject- 4
Save);
, (
Cancel);
savestate () - QByteArray ;
restoreState (<QByteArray>) -
QFileDialog :
626
directoryEntered(const
11.
QString&}- .
fileSelected(const QString&}- .
;
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,
(<>,
<>}.
. :
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:
27.8.
27.12.
27.12.
Q~rroressage u
(.
27.13).
, . ,
. QErroressage :
QErrorMessage:
QErrorMessage([parent=None])
632
'-i)
11.
L oom-oo-..
,. ~~~ . . . .
27.13.
.....
. ..
. - - ....-.... .... ]
n~r
27.9.
QProgressDialog u
Ca ncel ( . 27.14).
11
QProgressDialog :
QProgressDialog([parent=None] [, flags=OJJ
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
m1111 nu
fiiiiiiiiiiiiiiiil
.
27.14.
J ~s:ot.
t
t
27.
633
value () - ;
setLabelText (< >) .
setCancelButtonText (<
Cancel.
Cancel>) -
setCancelButtonext (const
QString&);
setRange (<>,
setMaximum (<>) -
. ,
,
setMaximum()
setMinimumDuration (<>) -
setMinimum(int)
setMinimum ()
setMaximum(int);
( 4000).
setMinimumDuration(int);
t
t
t
reset () - . ;
cancel () - Cancel. ;
setAutoClose (<>) - True,
;
wascanceled () - True, \.
Cancel.
27.1 .
QWizard QWizardPage ,
( )
Back
()
Next
(). QWizard ,
27.1 0.1.
QWizardPage.
QWizard
QWizard ,
. QWizard :
QWizard([parent=None] [, flags=O])
QWizard
( ;
):
634
11.
+
+
+
QWizardPage), , None,
;
+
+
+
pageids () - ;
setStart Id ( <11>) - ;
+
+
startld () - ;
current Id () -
curr~ntPage ()
QWizardPage) None, ;
visi tedPages () ;
+
+
+
+
back () - 1\ Back. ;
next () - Next. ;
restart () -
. ;
nextrd (self) ,
QWizarcl. . i
Next.
-1;
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;
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-
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 -
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 :
QWizardPage:
= QWizardPage ( [parent=NoneJ.)
QWizardPage ~1
( ;
):
+
+
+
+
+
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 (<>) -
,
;
Finish;
isFinalPage () - True,
Finish, False- ;
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
Finish.
n .
n.
28
PyQt
SDI-
DI-
n n :
SDI-npuoeu
. , n
n n n. n n n
n ,
WordPad
Paint
Windows.
SDI-n, n n
setCentralWidget ()
D/-u
QainWindow;
. n
n DI-n n
Photoshop,
. DI-n,
n n
QMdiArea
28.1.
QMainWindow n, , n
, nn n, n .
QMainWindow
[,
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 . <>
n ,
(
<QToo1Bar 2>) -
QToo1Bar);
n <QToo1Bar
2> n
n <Qoo1Bar
removeoo1Bar(<QToo1Bar>)- n .
toolBarArea ( <QToo1Bar>) -
+
+
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 ().
. <>
Horizontal,
Vertical- ;
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--:
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>,
. <>.
1>
, <QDockWidget 2> ,
. :
taifyDockWidget (<QDockWidget
<QDockWidget
1>,
<>)
<QDockWidget
2> <QDockWidget
2>) -
1>, , ,
taifiedDockWidgets (<QDockWidget>) -
QDockWidget), ,
;
saveState ( [version=O]) -
QByteArray
(,
),
restoreState(<QByteArray>[, version=O]).
,
QWidget. QByteArray .
restoreGeometry(<QByteArray>);
restoreDockWidget (<QDockWidget>) -
28.2.
Fa1se-
,
, .
( QMenuBar),
( QMenu) .
( QAction),
, . ,
, .
.
QMenu
contextMenuEvent () _ (),
28.
28.2.1.
SD/-
645
D/-
QMenuBar
QMenuar .
.
menuBar ()
QMainWindow.
QWidget -
QMenuBar
QMenuar :
<>= QenuBar([parent=<Poe>])
QMenuar
( ;
u):
addenu ( <Qenu>) -
QAct ion,
, , ( setVisie ())
( setEnaed () );
addenu ( [ <Qicon>,
J <>) -
( QMenu). <>
&, u, u
. &, ,
<Ait>
. &, ;
insertMenu (<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
, ,
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-
<QAction 2>) -
<QAction 2>
<:
insertActions (<QAction>,
QAction>) -
<QAction>;
- (
actions ()
removeAction (<QAction>)
QAction);
- ;
addSeparator () QAction;
insertSeparator (<QAction>) -
QAction;
addenu ( <Qenu>) -
addenu
( [<Qicon>, ] <>) -
QAction;
QMenu);
c1ear ()
isEmpty () -
Fa1se- ;
menuAction () -
- ;
rue, ,
QAction),
. (
setVisile ()) ( setEnaled
ti t1e () -
seticon (<Qicon>)
icon ()
setActiveAction (<QAction>)
setDe_fau1tAction ( <QAction>)
( l );
- ;
;
- ;
- (
Qicon);
- ;
QAction)
- _ ;
defau1tAction () None;
QAction)
setTearOffEnaed(<a>)--
True,
(
, );
isTearOffEnaed
Fa1se--
() -
True,
isTearOffenuVisile
() - rue,
Fa1se-- ;
hideTearOffenu
()
- ;
648
11.
. , , , ;
popup ( <QPoint> [,
<QAction>] ) -
. , ,
;
_ ( [ <QPoint> [,
<QAction>]]) -
QAction ( )
None ( , ,
<Esc>).
, ,
.
_ ().
QAction ( ) None ( ,
,
_(<
<Esc> ).
_(<
<QWidget>)
<QAction>, ,
<QWidget>
.
.
QMenu :
hovered (QAction
*) -
triggered (QAction *) -
_OAction;
aboutoshow () -
aboutToHide () - .
28.2.3.
QAction;
(J ( J -
pos () -
QPoint
globalX() globalY()-
;
globalPos () - QPoint .
28.
SDI-
649
D/-
contextMenuEvent ().
() globalPos ().
context _ menu. ,
contextMenuEvent (! .
28.2.4.
QAction
QAction , ,
- .
. ,
, .
QAction :
QObject - QAction
<>
QAction:
QAction(<QObject>)
<>
Qtin(<>,
<>
QAction(<Qicon>,
<QObject>)
<QObject>)
<>,
<Ait>
&, .
<Qicon> .
QAction ( ;
):
+
+
+
+
text () -
seticon (<Qicon>) - ;
icon () - ( Qicon);
seticonVisieinenu (<>) - F'alse,
11 ;
setSeparator (<>) -
't rue,
isSeparator () True, ,
False - ;
650
11.
"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 >)
< >
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
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
652
+
+
1/.
. -
+
+
+
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;
. False .
'
setExclusive (bool);
28.
SDI-
setDis.aed (<>)
D/-
653
True,
. False
.
setEnaed (<>)
False,
True
. setEnaed (bo~l);
isEnaed
() -
rue, ,
False-
setVisie (<>) -
False,
True .
setVisie (bool);
isVisie
() - False, , True-
QActionGroup :
hovered (QAction
*) -
. .
(
QAction);
selected (QAction *) -
, .
( QAction);
, .
( QAction).
28.3.
addToolBar {)
, .
. , ,
setAllowedAreas () QToolBar,
().
setFloatae
28.3.1.
QToo/Bar
QToolBar ,
. QToolBar :
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:
insertActions (<QAction>,
<
QAction>) -
+
+
actions () - ( QAction);
removeAction (<QAction>) -
. ;
addSeparator () - QAction;
insertseparator ( <QAction>)
addWidget (<QWidget>) -
QAction;
, ,
<QAction>;
QAction;
.r
widgetForAction (<QAction>) -
+
+
clear () - ;
setAllowedAreas (<>) -
. (
1)
setMovae (<>)
True (
False
), .
;
isMovae
,
() - rue,
False- ;
28.
SDI-
/-
655
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;
rue, , F'alse ;
topLevelChanged(bool)- .
rue,
, F'alse- .
28.3.2. accQToo/Button
,
QToolButton.
widgetF'orAction(<;QAction>)
QToolar.
QoolButton :
QAstractButton
QoolButton
QToolButton :
<>= QToolButton([parent=<Poe>])
656
11.
QToolutton n
(n ; n n
):
setDefaultAction ( <QAction>) - n.
setDefaultAction (QAction *);
defaultAction () -
(n QAction),
n;
setoolButtonStyle (<>) - n.
<> . .
+
+
+
+
+
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,
n , n n .
n n n QAction.
28.4.
n n
, (n, n),
n
nn n.
n n n
QDockWidget. 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)
isFloating () - rue, ,
False- ;
setFeatures (<>)- .
(
DockWidgetClosable-
DockWidgetMovable-
1)
QDockWidget:
n ;
DockWidgetFloatable- ;
DockWidgetVerticalTitleBar- ,
;
NoDockWidgetFeatures- n ,
;
+
+
features () - ;
toggleViewAction () -
( QAction),
n.
QoockWidget ( ;
):
658
11.
,
;
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>).
QStatusBar
( ;
):
. , ,
l) clearessage ().
\+
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 .
28.6.
DI-
DI-n
. DI-n,
n n
QMdiArea
28.6.1.
QMdiArea
QMdiArea DI-, n
(n QMdiSuWindow). QMdiArea
:
- 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 ,
<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;
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-;
North-
South- 1 - ;
West -
2-
East -
- ;
;
n;
tabPosition (<>) n n
n TabbedView;
setTabShape (<>) - n
TabbedView. QTabWidget:
Rounded- - ( );
Triangular- 1 - ;
~abShape () -
+
+
TabbedView;
n True,
, False- . n <>
DontMaximizeSuWindoWOnActivation QMdiArea.
662
U.
, r-t
;
-r . 11
( QMdiSuWindow)
None.
28.6.2.
QMdiSubWindow .
QMdiSuWindow , DI-.
QMdiSuWindow :
QdiSuWindow
QMdiSuWindo;.:
<>= QdiSuWindow([parent=<Poe>]
[,
flags=<T >])
QMdiSuWindow
. ( ;
):
setWidget (<QWidget>) - ;
widget () - ;
setSystemenu(<Qenu>)-
;
systemenu ()
( QMenu)
None;
showsystemenu () -
setKeyboardSingleStep(<aee>)-
.
,
Move
Size.
s;
setKeyboardPageStep (<>) -
<Shift>.
- 20;
showShaded () -
, .
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 ;
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
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
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
. 13~9
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
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
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
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
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
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
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
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
688
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
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
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
696
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
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
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
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,
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