Python Cheet Sheet

Python Naming Styles

变量命名基本规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# see: PEP8
# for public use
var
# for internal use
_var
# convention to avoid conflict keyword
var_
# for private use in class
__var
# for protect use in class
_var_
# "magic" method or attributes
# ex: __init__, __file__, __main__
__var__
# for "internal" use throwaway variable
# usually used in loop
# ex: [_ for _ in range(10)]
# or variable not used
# for _, a in [(1,2),(3,4)]: print a
_

Representations of your class behave

__str____repr__的区别

1
2
3
4
5
6
7
8
9
10
>>> class example(object):
... def __str__(self):
... return "example __str__"
... def __repr__(self):
... return "example __repr__"
...
>>> print str(example())
example __str__
>>> example()
example __repr__

for: exp else: exp

for…else…结构,若循环中没有发生break,则进入else部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# see document: More Control Flow Tools
# forloop’s else clause runs when no break occurs
>>> for _ in range(5):
... print _,
... else:
... print "\nno break occur"
...
0 1 2 3 4
no break occur
>>> for _ in range(5):
... if _ % 2 ==0:
... print "break occur"
... break
... else:
... print "else not occur"
...
break occur
# above statement equivalent to
flag = False
for _ in range(5):
if _ % 2 == 0:
flag = True
print "break occur"
break
if flag == False:
print "else not occur"

try: exp else: exp

1
2
3
4
5
6
7
8
9
10
# No exception occur will go into else.
>>> try:
... print "No exception"
... except:
... pass
... else:
... print "else occur"
...
No exception
else occur

Get future features

未来可能会加入的新的语言特性。

1
2
3
4
5
6
7
8
9
10
11
12
# programmers can use to enable new language features
# see: https://docs.python.org/2/glossary.html
# for example: print function
>>> f = lambda: print("ker")
File "<stdin>", line 1
f = lambda: print("ker")
^
SyntaxError: invalid syntax
>>> from __future__ import print_function
>>> f = lambda: print("ker")
>>> f()
ker

Check object attributes

某种角度说是python的反射机制。

1
2
3
# example of check list attributes
>>> dir(list)
['__add__', '__class__', ...]

Define a function doc

定义说明文件(doc)

1
2
3
4
5
6
7
8
9
10
# Define a function document
>>> def Example():
... """ This is an example function """
... print "Example function"
...
>>> Example.__doc__
' This is an example function '
# Or using help function
>>> help(Example)

Check instance type

1
2
3
>>> ex = 10
>>> isinstance(ex,int)
True

Check, Get, Set attributes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
>>> class example(object):
... def __init__(self):
... self.name = "ex"
... def printex(self):
... print "This is an example"
...
# Check object has attributes
# hasattr(obj, 'attr')
>>> ex = example()
>>> hasattr(ex,"name")
True
>>> hasattr(ex,"printex")
True
>>> hasattr(ex,"print")
False
# Get object attribute
# getattr(obj, 'attr')
>>> getattr(ex,'name')
'ex'
# Set object attribute
# setattr(obj, 'attr', value)
>>> setattr(ex,'name','example')
>>> ex.name
'example'

Check inheritance

检查继承关系

1
2
3
4
5
6
7
8
>>> class example(object):
... def __init__(self):
... self.name = "ex"
... def printex(self):
... print "This is an example"
...
>>> issubclass(example,object)
True

Check all global variables

1
2
3
4
# globals() return a dictionary
# {'variable name': variable value}
>>> globals()
{'args': (1, 2, 3, 4, 5), ...}

Check “callable”

1
2
3
4
5
6
7
8
>>> a = 10
>>> def fun():
... print "I am callable"
...
>>> callable(a)
False
>>> callable(fun)
True

Get function/class name

1
2
3
4
5
6
7
8
9
10
>>> class excls(object):
... pass
...
>>> def exfun():
... pass
...
>>> ex.__class__.__name__
'excls'
>>> exfun.__name__
'exfun'

Common Use “Magic”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# see python document: data model
# For command class
__main__
__name__
__file__
__module__
__all__
__dict__
__class__
__doc__
__init__(self, [...)
__str__(self)
__repr__(self)
__del__(self)
# For Descriptor
__get__(self, instance, owner)
__set__(self, instance, value)
__delete__(self, instance)
# For Context Manager
__enter__(self)
__exit__(self, exc_ty, exc_val, tb)
# Emulating container types
__len__(self)
__getitem__(self, key)
__setitem__(self, key, value)
__delitem__(self, key)
__iter__(self)
__contains__(self, value)
# Controlling Attribute Access
__getattr__(self, name)
__setattr__(self, name, value)
__delattr__(self, name)
__getattribute__(self, name)
# Callable object
__call__(self, [args...])
# Compare related
__cmp__(self, other)
__eq__(self, other)
__ne__(self, other)
__lt__(self, other)
__gt__(self, other)
__le__(self, other)
__ge__(self, other)
# arithmetical operation related
__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__div__(self, other)
__mod__(self, other)
__and__(self, other)
__or__(self, other)
__xor__(self, other)

Arithmetic operators and Comparison

常见算数运算重载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class example(object):
def __init__(self,val1,val2):
self.val1 = val1
self.val2 = val2
def __add__(self,other):
_1 = self.val1 + other.val1
_2 = self.val2 + other.val2
return _1 + _2
def __sub__(self,other):
_1 = self.val1 - other.val1
_2 = self.val2 - other.val2
return _1 - _2
def __mul__(self,other):
_1 = self.val1 * other.val1
_2 = self.val2 * other.val2
return _1 * _2
def __div__(self,other):
_1 = self.val1 / other.val1
_2 = self.val2 / other.val2
return _1 / _2
def __mod__(self,other):
_1 = self.val1 % other.val1
_2 = self.val2 % other.val2
return _1 % _2
def __eq__(self,other):
if self.val1 == other.val1 and\
self.val2 == other.val2:
return True
return False
def __ne__(self,other):
if self.val1 != other.val1 or\
self.val2 != other.val2:
return True
return False
def __lt__(self,other):
if self.val1 < other.val1 or\
self.val2 < other.val2:
return True
return False
def __gt__(self,other):
if self.val1 > other.val1 or\
self.val2 > other.val2:
return True
return False
def __le__(self,other):
if self.val1 <= other.val1 or\
self.val2 <= other.val2:
return True
return False
def __ge__(self,other):
if self.val1 >= other.val1 or\
self.val2 >= other.val2:
return True
return False
# example result:
>>> ex1 = example(1.,2.)
>>> ex2 = example(3.,4.)
>>> ex1+ex2
10.0
>>> ex1-ex2
0.0
>>> ex1*ex2
24.0
>>> ex1/ex2
0.6666666666666666
>>> ex1%ex2
1.0
>>> ex1>ex2
False
>>> ex1<ex2
True
>>> ex1==ex2
False

Get list item “SMART”

一些切片、迭代器与过滤器的技巧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
>>> a = [1,2,3,4,5]
>>> a[0]
1
>>>a[-1]
5
>>> a[0:]
[1,2,3,4,5]
>>> a[:-1]
[1,2,3,4]
# a[start:end:step]
>>> a[0:-1:2]
[1,3]
# using slice object
# slice(start,end,step)
>>> s = slice(0,-1,2)
>>> a[s]
[1,3]
# Get index and item in loop
>>> a = range(3)
>>> for idx,item in enumerate(a):
... print (idx,item),
...
(0, 0) (1, 1) (2, 2)
# Transfer two list into tuple list
>>> a = [1,2,3,4,5]
>>> b = [2,4,5,6,8]
>>> zip(a,b)
[(1, 2), (2, 4), (3, 5), (4, 6), (5, 8)]
# with filter
>>> [x for x in range(5) if x>1]
[2, 3, 4]
>>> _ = ['1','2',3,'Hello',4]
>>> f = lambda x: isinstance(x,int)
>>> filter(f,_)
[3, 4]

Get dictionary item “SMART”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# get dictionary all keys
>>> a={"1":1,"2":2,"3":3}
>>> b={"2":2,"3":3,"4":4}
>>> a.keys()
['1', '3', '2']
# get dictionary key and value as tuple
>>> a.items()
[('1', 1), ('3', 3), ('2', 2)]
# find same key between two dictionary
>>> [_ for _ in a.keys() if _ in b.keys()]
['3', '2']
# better way
>>> c = set(a).intersection(set(b))
>>> list(c)
['3', '2']
# or
>>> [_ for _ in a if _ in b]
['3', '2']
# update dictionary
>>> a.update(b)
>>> a
{'1': 1, '3': 3, '2': 2, '4': 4}

Set a list/dict “SMART”

1
2
In [12]: {'{0}'.format(x): '{0}+{1}'.format(x,x+1) for x in range(3)}
Out[12]: {'0': '0+1', '1': '1+2', '2': '2+3'}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# get a list with init value
>>> ex = [0]*10
>>> ex
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# extend two list
>>> a = [1,2,3]; b=['a','b']
>>> a+b
[1, 2, 3, 'a', 'b']
# using generator
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> fn = lambda x: x**2
>>> [fn(x) for x in range(5)]
[0, 1, 4, 9, 16]
>>> {'{0}'.format(x): x for x in range(3)}
{'1': 1, '0': 0, '2': 2}
# using builtin function "map"
>>> map(fn,range(5))
[0, 1, 4, 9, 16]

NamedTuple

1
2
3
4
5
6
7
8
# namedtuple(typename, field_names)
# replace define class without method
# see: python document collections
>>> from collections import namedtuple
>>> ex = namedtuple("ex",'a b c')
>>> e = ex(1,2,3)
>>> print e.a, e[1], e[1]+e.b
1 2 4

Delegating Iteration (iter)

1
2
3
4
5
6
7
8
9
10
11
12
# __iter__ return an iterator object
# Be careful: list is an "iterable" object not an "iterator"
>>> class example(object):
... def __init__(self,list_):
... self._list = list_
... def __iter__(self):
... return iter(self._list)
...
>>> ex = example([1,2,3,4,5])
>>> for _ in ex: print _,
...
1 2 3 4 5

Using Generator as Iterator

# see: PEP289
>>> a = (_ for _ in range(10))
>>> for _ in a: print _,
... 
0 1 2 3 4 5 6 7 8 9

# equivalent to
>>> def _gen():
...   for _ in range(10):
...     yield _
... 
>>> a = _gen()
>>> for _ in a: print _,
... 
0 1 2 3 4 5 6 7 8 9

参考资料

[1] Python Cheet Sheet