pYTHON again

Pick python up from a link for new position:

type

1
2
type(123)
isinstance(instance_name, class_name)

@property

transfer get()method in a class to a decorator

define function

1
2
3
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')

fun decorator

1
2
@decorator
def fun()

filter

1
2
3
4
def is_odd(n):
return n%2 == 1
list(filter(is_odd, [1, 2, 3, 4])

lambda

1
list(map(lambda x: x*2, [1, 2, 3, 4]))

slice

1
2
L = [1, 2, 3, 4, 5]
L[-2:] #[4, 5]

list generation

1
[x*2 for x in range(1, 5)]

class & instance

1
2
3
4
5
6
7
8
9
class s(object):
def \__init__(self, name):
self.name = name
def print_s(self):
print('%s:' %(self.name))
s1 = s("john")
s1.print_s()

customized class

dynamic language, so the instance of any class can be added any other attributes.

1
2
3
4
5
6
7
8
9
class s(object):
def \__init__(self, name):
self._name = name
def \__str__(self):
return 's object(name: %s)' % self._name
def \__getattr__(self, attr):
if attr == 'attr1':
return lambda: attr1.value

raise & except

1
2
3
4
5
6
7
8
9
10
11
import logging
try:
print('try...')
r = 10/0
print('result: ', r)
except ZeroDiisionError as e:
print('except', e)
logging.exception(e)
finally:
print('finally..')

IO stream

1
2
3
4
5
6
7
8
9
10
11
f = open('test.log', 'r')
print(f.read(size))
f.close()
#or
with open('test.log', 'r') as f:
printf(f.read(size))
for line in f.readlines():
print(line.strip())

pickling

serializaion/marshalling/flattening and reverse

1
2
3
4
5
6
import pickle
import json
d = dic(name='zj', age='18')
pickle.dumps(d)
json.dumps(d)