kalamar python-3-core

До загрузки: 30 сек.



Благодарим, что скачиваете у нас :)

Если, что - то:

  • Поделится ссылкой:
  • Документ найден в свободном доступе.
  • Загрузка документа - бесплатна.
  • Если нарушены ваши права, свяжитесь с нами.
Формат: pdf
Найдено: 28.08.2020
Добавлено: 30.09.2020
Размер: 0.07 Мб

Pyth on 3 C ore C heat S heet
by
Kala m ar
v ia
ch eato gra phy.c o m /5 3430/c s/1 4422/
V ir tu al E nvir o
​nm en t s etu p
sudo pip install virtualenv # sudo may by optional
mkdir testenv
cd testenv
virtu
​alenv -p $( which python3.4 ) .lpvenv
source .lpven
​v/b
​in/
​act
​ivate
This s e t o f c o m mands is fo r a u nix -lik e e nvir o
​nm ent, b ut a s im ila r s e tu p
ca n b e d one o n W in dow s.
C ore t y p es
In te gers : u nlim it e d
ca st:
int(v
​alue)
B oole an:
True
​/ F ​alse
ca st:
bool(
​value)

any n on-z e ro is
True
R eal: 6 4 b it s
D ecim al: a rb it r a ry p re cis io n
from decimal import Decimal
C om ple x:
1 + 2j
meth ods:
real
,
imag
S tr in gs
""
em pty s tr in g
len(v
​alue)
built - in to g et th e le ngth
s[start:stop:step]
slic in g, s ta rt/
​sto
​p/s te p a re o ptio nal, s to p is n on-
in
​clu siv e
s.enc
​ode
​('u
​tf-8')
utf- 8 e nco ded v e rs io n o f s , b yte s o bje ct
b"s
​tri
​ng"
byte s o bje ct
Tuple s
()
em pty tu ple
(val,)
1-e le m ent tu ple , c o m ma is r e quir e d
(a,b,c)
generic s yn ta x fo r tu ple s
a,b,c = 1,2,3
im plic it o n a ssig nm ent
Tuple s a re im muta ble
Lis ts
[]
o r lis t( )
em pty lis t
list(
​(cr
​eate, from, a, tuple))
_
[x + 5 for x in (1,2,3)]
defin it io n b y c o m pre
​hensio n
+ co nca t
​enate lis ts
* re peat lis t
Nota ble m eth ods:
append(x), count(x), extend(list),
index(x), insert(pos,value), pop(), pop(pos),
remove(val), reverse(), sort(), clear()
Nota ble fu nctio ns:
min(list), max(list), sum(list),
len(list)
Dic tio
​narie s
dict()
o r
{}
em pty d ic tio nary
Equiv a le nt d efin i
​tio ns
dict(A=1, Z=-1)

{'A': 1, 'Z': -1}

dict(
​zip
​(['A', 'Z'], [1, -1]))

dict(
​[('A', 1), ('Z', -1)])

dict(
​{'Z': -1, 'A': 1})
Nota ble o pera tio ns:
len, del, in
Nota ble m eth ods:
clear(), keys(), values(), items(),
popitem(), pop(key), update({key, value}),
update(key=value), get(key), setdefault
Sets
set()
em pty s e t
value in set
te st fo r p re se nce
Muta ble , fo r im muta ble , u se fr o ze nse t.
Nota ble m eth ods:
add(x), remove(x)
Condit io ns
if condition:
​ ​ ​ ​stuff
else:
​ ​ ​ ​stuff
if condition:
​ ​ ​ ​stuff
elif condit
​ion2:
​ ​ ​ ​stuff
By
Kala m ar
ch eato gra phy.c o m /k a la m ar/
Publis h ed 1 4th F ebru ary , 2 018.
Last u pdate d 1 4th F ebru ary , 2 018.
Page 1 o f 4 .
Sponso re d b y
Read ab ilit y -S co re .c o m
Measu re y o ur w ebsit e r e adabilit y !
http s://r e adabilit y -s co re .c o m

Pyth on 3 C ore C heat S heet
by
Kala m ar
v ia
ch eato gra phy.c o m /5 3430/c s/1 4422/
C ondit io ns ( c o nt)
elif condit
​ion3:
​ ​ ​ ​stuff
else:
​ ​ ​ ​stuff
ternary = a if condition else b
It e ra tio n
for i in range(start,stop,step):
​ ​ ​ ​stuff
for value in [seque
​nce]:
​ ​ ​ ​stuff
for position, value in enumer
​ate
​(se
​que
​nce):
​ ​ ​ ​stuff
for a,b in zip(first, second):
​ ​ ​stuff
for ###
else
​ ​ ​ ​stuff to do at end of loop (usually exception when
breaking in loop)
while condition:
​ ​ ​ ​stuff
else
​ ​ ​ ​stuff to do when condition is false
break # breaks the loop
continue # continue at the start of the loop body
m odule it e rto ols p ro vid es lo ts o f in te re
​stin g to ols fo r it e ra tio n
E xcep tio ns
try:
​ ​ ​ # do something
​ ​except Except
​ionName as e:
​ ​ ​ # do something
​ ​except (Excep
​tio
​nName, OtherE
​xce
​ption) as e:
​ ​ ​ # do something
​ ​else:
​ ​ ​ # do something when no exception
​ ​fin
​ally:
Excep tio ns ( c o nt)
​ ​ ​ # do something anyway, exception or not
Functio ns
def function_name(args):
body
nonlocal variab
​le_
​name
acce ss to n eare st e nclo sin g s co pe fo r
va ria ble
global variab
​le_
​name
acce ss g lo bal s co pe v a ria ble
def func(a
​,b,c):
sta ndard p osit io nal a rg s
func(c=1, b=2, a=3)
ca ll u sin g k e yw ord s
def func(a
​,b=
​55,
​c=85:)
defa ult v a lu es fo r m is sin g a rg s, !! b e
wary o f m uta ble d efa ult s
def func(*n):
va ria ble a rg lis t, a ddre sse d a s a n a rra y
func(*n)
ca lls fu nc u npackin g a rra y a rg um ent
def func(**
​kw
​args):
va ria ble k e yw ord a rg um ents , a ddre sse d
as a d ic t
func(
​**n)
ca lls fu nc u npackin g d ic t a rg um ent
pass
em pty b ody m eth od
return a,b,c
re tu rn m ult ip le v a lu es
lambda
[param
​ete
​r_l
​ist]:
expres
​sion
fo r s m all s n ip pets
def func(n):
"""documentation, possibly multiline"""
pass
Specia l a ttr ib ute s:
__doc__, __name__, __qualname__,
__module__, __defaults__, __code__, __globals__,
__dict__, __closure__, __annotations__, __kwdefaults__
built in s:
abs all any ascii bin callable chr compile
delattr dir divmod eval exec format getattr globals
hasattr hash hex id input isinstance issubclass iter
len locals max min next oct open ord pow print repr
round setattr sorted sum vars
By
Kala m ar
ch eato gra phy.c o m /k a la m ar/
Publis h ed 1 4th F ebru ary , 2 018.
Last u pdate d 1 4th F ebru ary , 2 018.
Page 2 o f 4 .
Sponso re d b y
Read ab ilit y -S co re .c o m
Measu re y o ur w ebsit e r e adabilit y !
http s://r e adabilit y -s co re .c o m

Pyth on 3 C ore C heat S heet
by
Kala m ar
v ia
ch eato gra phy.c o m /5 3430/c s/1 4422/
U tilit ie s
map(f
​unc
​tion,
iterable,
option
​al_
​ite
​rable,
...)
re tu rn s it e ra to r w hic h w ill a pply fu nctio n o n
each v a lu e o f th e it e ra ble s, s to ppin g a t fir s t
exh auste d it e ra ble
zip(*
​ite
​rab
​les)
re tu rn s it e ra to r o f tu ple s, in te rl
​acin g th e
it e ra ble s, s to ps a t fir s t e xh auste d it e ra ble
filte
​r(f
​unc
​tion,
iterable)
re tu rn s it e ra to r fr o m th ose e le m ents o f
it e ra ble fo r w hic h fu nctio n r e tu rn s T ru e
C om pre
​hen
​sio ns
lis t
[ expression for iterab
​le_
​clause if
option
​al_
​fil
​ter]
neste d
lis ts
[ expression for iterab
​le_
​cla
​use_1 for
iterab
​le_
​cla
​use_2 if option
​al_
​fil
​ter]
dic t
{ key_ex
​pre
​ssion: value_
​exp
​ression for
iterab
​le_
​clause if option
​al_
​fil
​ter}
se t
{ value_
​exp
​ression for iterab
​le_
​clause if
option
​al_
​fil
​ter}
G en era to r f u nctio ns
yield x
re tu rn s th e v a lu e x , s u sp ends a nd s to re s
th e in te rn al s ta te
next(
​fun
​ction)
re su m es e xe cu tio n ( o r s ta rt th e fir s t tim e)
until lo op e nds w it h n o v a lu e o r S to pIt
​era tio n is r a is e d
gener
​ato
​r.s
​end(x)
re su m es a nd m ake s x a s th e r e tu rn v a lu e
of y ie ld
usa ge e xa m ple :
for in in
genera
​tor
​_fu
​nct
​ion
​(**
​som
​e_p
​arams)
yield from
list_c
​omp
​reh
​ension
adva nce d p atte rn
Gen era to r e xp re ssio n
lik e a lis t c o m pre
​hensio n b ut ( ) in ste ad o f []
re tu rn s 1 it e m a t a tim e
easie r to r e ad th an m ap+ filt e r
Deco ra to rs
def wrap(func):
​ ​ ​ def wrappe
​r(
​*args, **kw
​args):
​ ​ ​ ​ ​ ​ ​ # do something about func
​ ​ ​ ​ ​ ​ ​ ​fun
​c(
​*args, **kw
​args)
​ ​ ​ ​ ​ ​ ​ # do something about func
​ ​ ​ ​return wrapper
# Apply decorator
def to_dec
​ora
​te(...):
# body
to_dec
​orate = wrap(t
​o_d
​eco
​rate)
# More idiomatic
@wrap
def to_dec
​ora
​te(...):
#body
from functools import wraps
@wraps
​(func)
def wrappe
​r(...) # to keep the name and doc from the
wrapped function
# Decorator with args: make a decorator factory
def decora
​tor
​_fa
​cto
​ry(
​fac
​tor
​y_a
​rgs):
​ ​ ​ def decora
​tor
​(func):
​ ​ ​ ​ ​ ​ ​ def wrappe
​r(
​*args, **kw
​args):
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ # do something about func
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​fun
​c(
​*args, **kw
​args)
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ # do something about func
​ ​ ​ ​ ​ ​ ​ ​return wrapper
​ ​ ​ ​return decorator
@decor
​ato
​r_f
​act
​ory
​(1,
​2...)
def to_dec
​ora
​te(...):
Mult ip le d eco ra
​to rs : th e c lo se r th e d eco ra to r to th e fu nctio n, th e s o oner it is
applie d.
By
Kala m ar
ch eato gra phy.c o m /k a la m ar/
Publis h ed 1 4th F ebru ary , 2 018.
Last u pdate d 1 4th F ebru ary , 2 018.
Page 3 o f 4 .
Sponso re d b y
Read ab ilit y -S co re .c o m
Measu re y o ur w ebsit e r e adabilit y !
http s://r e adabilit y -s co re .c o m

Pyth on 3 C ore C heat S heet
by
Kala m ar
v ia
ch eato gra phy.c o m /5 3430/c s/1 4422/
C la sses
class Child(Parent):
is -a in heri
​ta nce
class
Child(
​Mul
​tiple,
Parent):
Child.mro()
r e tu rn s M eth od R eso lu tio n
Ord er
def __init
​(self,
args):
in it ia
​liz e r
super
​()._
​_i
​nit
​__(
​sel
f, some_a
​rgs)
ca ll p are nt in it ia
​liz e r
def
instan
​ce_
​met
​hod
​(self
, args):
self
is a c o nve ntio n fo r th e fir s t a rg um ent,
th e im plic it in sta nce
instance =
ClassN
​ame
​(pa
​rams)
cre ate in sta nce
@stat
​icm
​ethod
annota tio n fo r s ta tic m eth od, n o s p ecia l
arg um ent ( lik e
self
)
@classmethod
annota tio n fo r s ta tic m eth od, s p ecia l
arg um ent is th e c la ss o bje ct it s e lf
(c o nve
​ntio n:
cls
). U sa ge: fa cto ry m eth ods
or e xtr a ctin g s u b-m e
​th ods fr o m
@sta ti
​cm e
​th ods m eth ods ( to a vo id h avin g a
hard -c o ded c la ss n am e w hen c a llin g th em )
_attr
​ibute
pse udo p riv a te a ttr ib ute ( c o nve
​ntio n)
__som
​e_a
​ttr
​_or
​_me
​tho
d alm ost p riv a te th ro ugh n am e m anglin g
@prop
​erty
fo r g ette r
@prop
​ert
​y.s
​etter
fo r s e tte r
a c la ss is a s u bcla ss o f it s e lf ; a ttr ib ute s c a n b e a dded in d ecla r
​atio n ( c la ss
attr ib
​ute s) o r d yn am i
​ca lly to in sta nce o r c la ss
Custo m It e ra tio n
it e ra ble m ust d efin e
__iter__
o r
__get
​_it
​em__
it e ra to r m ust d efin e
__iter__
( re tu rn in g s e lf ) a nd
__next__
( ra is e
StopI
​ter
​ation
a t th e e nd)
usa ge:
for i in iterable:
By
Kala m ar
ch eato gra phy.c o m /k a la m ar/
Publis h ed 1 4th F ebru ary , 2 018.
Last u pdate d 1 4th F ebru ary , 2 018.
Page 4 o f 4 .
Sponso re d b y
Read ab ilit y -S co re .c o m
Measu re y o ur w ebsit e r e adabilit y !
http s://r e adabilit y -s co re .c o m

Сообщить о нарушении / Abuse

Все документы на сайте взяты из открытых источников, которые размещаются пользователями. Приносим свои глубочайшие извинения, если Ваш документ был опубликован без Вашего на то согласия.