1. 小技巧
[toc]
1.1. 杂
获取当前路径: os.getcwd()
获取库中所有变量、类名 : dir(库名)
协程:类似子例程,或者说是不带返回值的函数调用
python第三方库 gevent
为python提供了比较完善的协程支持。
自建迭代器:需要实现 __iter__()
和 __next__()
方法。
1.2. format简略写法
print('a+b={}'.format(a+b))
print(f'a+b={a+b}')
1.3. __slots__
python是动态语言,可以在运行的过程中,修改代码。如果想限制实例的属性,可以使用 __slots__
。
class Person:
__slots__ = ("name", "age")
Person类只有name/age2个属性可以赋值。如果想增加其他属性,会出错。
注:__slots__
定义的属性仅对当前类实例起作用,对继承的子类不起作用
1.4. 通过URL打开图片
import requests as req
from PIL import Image
from io import BytesIO
img_src = 'http://wx2.sinaimg.cn/mw690/ac38503ely1fesz8m0ov6j20qo140dix.jpg'
response = req.get(img_src)
image = Image.open(BytesIO(response.content))
image.show()
1.5. 字符串解码
因为decode的函数原型是 decode([encoding], [errors='strict'])
,可以用第二个参数控制错误处理的策略,默认的参数就是strict,代表遇到非法字符时抛出异常。
其他选项:
ignore
:忽略非法字符replace
:会用?取代非法字符xmlcharrefreplace
:使用XML的字符引用
1.6. 创建文件或目录
import os
file = 'hg.txt'
#判断文件是否存在
os.path.exists(file)
# 创建文件
os.mknod(file)
open(file, 'w')
# 创建文件夹
os.mkdir('aa/bb') # aa文件夹要存在才能创建
os.makedirs('aa/bb/cc') # 递归创建目录
1.7. 断言
断言:assert expression
/ assert expression, arguments
等价于:
if not expression:
raise AssertionError
if not expression:
raise AssertionError(arguments)