本文首发于微信公众号:NewBeeNLP
Python Cookbook的下半部分笔记~
Chap 7 函数
将元数据信息附加到函数参数上
def add(x:int, y:int) -> int:
return x + y
help(add)
Help on function add in module __main__:
add(x:int, y:int) -> int
>>> add.__annotations__
{'x': , 'y': , 'return': }
让带有N个参数的可调用对象以较少的参数形式调用
In [14]: def spam(a, b, c, d):
...: print(a, b, c, d)
In [15]: from functools import partial
In [17]: s1 = partial(spam, 1)
In [18]: s1(2, 3, 4)
(1, 2, 3, 4)
In [19]: s1(4, 5, 6)
(1, 4, 5, 6)
In [20]: s2 = partial(spam, d=42)
In [21]: s2(4, 5, 5)
(4, 5, 5, 42)
In [24]: s3 = partial(spam, 1, 2, d=42)
In [25]: s3(5)
(1, 2, 5, 42)
In [26]: points = [ (1, 2), (3, 4), (5, 6), (7, 8) ]
In [27]: import math
In [28]: def distance(p1, p2):
...: x1, y1 = p1
...: x2, y2 = p2
...: return math.hypot(x2 - x1, y2 - y1)
In [29]: pt = (4, 3)
In [30]: points.sort(key=partial(distance, pt))
In [31]: points
Out[31]: [(3, 4), (1, 2), (5, 6), (7, 8)]
Chap 8 类与对象
修改实例的字符串表示
class Pair:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Pair ({0.x!r}, {0.y!r})'.format(self)
def __str__(self):
return '({0.x!s}, {0.y!s})'.format(self)
p = Pair(3, 4)
p
Pair(3, 4)
print(p)
(3, 4)
自定义字符串的输出格式
_formats = {
'ymd' : '{d.year} - {d.month} - {d.day}',
'mdy' : ...,
'dmy' : ...
}
class Date:
def __init__(self, year, month, day):
...
def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)
将名称封装到类中
创建可管理的属性
class Person:
def __init__(self, first_name):
self._first_name = first_name
# Getter function
@property
def first_name(self):
return self._first_name
# Setter function
@first_name.setter
def first_name(self, value):
if not isinstance(value, str):
raise TypeError('Expected a string')
self._first_name = value
# Deleter function
@first_name.deleter
def first_name(self):
raise AttributeError("Can't delete attribute")
import math
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return math.pi * self.radius ** 2
@property
def perimeter(self):
return 2 * math.pi * self.radius
c = Cirle(4.0)
c.radius
4
c.area
50.2654824
c.perimeter
25.132741228
Chap 9 元编程
元编程的主要目标是创建函数和类,并用他们来操纵代码。
给函数添加一个包装
import time
from fuctools import wraps
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def countdown(n):
...
#运行起来和下面代码的效果是一样的
def countdown(n):
....
countdown = timethis(countdown)
对装饰器进行解包装
@somedecorator
def add(x, y):
return x + y
>>> orig_add = add.__wrapped__
>>> orig_add(3, 4)
7
Chap 10 模块和包
把模块按层次结构组织成包
重新加载模块
import spam
import imp
imp.reload(spam)
读取包中的数据文件
import pkgutil
data = pkgutil.get_data(__package__,'somedata.dat')
Chap 12 并发
启动和停止进程
# Code to execute in an independent thread
import time
def countdown(n):
while n > 0:
print('T-minus', n)
n -= 1
time.sleep(5)
# Creat and lanch a thread
from threading import Thread
t = Thread(target=countdown, args=(10,))
t.start()
t = Thread(target=function,)
- END -
BERT源码分析(PART III) 几个Python“小伎俩” Transformers Assemble(PART I)