一些python的冷知识,万一用到了呢
finally中的return
1 2 3 4 5 6 7 8 9
| >>> def t(): ... try: ... return "123" ... finally: ... print("123456") ... >>> t() 123456 '123'
|
- finally中的return语句会覆盖try中的return语句
1 2 3 4 5 6 7 8
| >>> def t(): ... try: ... return "123" ... finally: ... return "123456" ... >>> t() '123456'
|
+= 与 =+的差异
+=
不涉及新对象的创建,而=+
语句会产生新对象然后再赋值
1 2 3 4 5 6 7
| >>> a = [1, 2] >>> b = a >>> a += [3, 4] >>> a [1, 2, 3, 4] >>> b [1, 2, 3, 4]
|
1 2 3 4 5 6 7
| >>> a = [1, 2] >>> b = a >>> a = a + [3, 4] >>> a [1, 2, 3, 4] >>> b [1, 2]
|
便捷查看包搜索路径
1 2 3 4 5 6 7 8 9 10 11
| ❯ python3 -m site sys.path = [ '/Users/yux1a0', '/Users/yux1a0/.pyenv/versions/3.6.8/lib/python36.zip', '/Users/yux1a0/.pyenv/versions/3.6.8/lib/python3.6', '/Users/yux1a0/.pyenv/versions/3.6.8/lib/python3.6/lib-dynload', '/Users/yux1a0/.pyenv/versions/3.6.8/lib/python3.6/site-packages', ] USER_BASE: '/Users/yux1a0/.local' (exists) USER_SITE: '/Users/yux1a0/.local/lib/python3.6/site-packages' (doesn't exist) ENABLE_USER_SITE: True
|
脚本出错或结束进入调试模式
python -i <pyfile>
用上下文管理器来处理错误
当类的成员函数都需要统一的错误处理的时候,可以用__exit__
来捕获错误
1 2 3 4 5 6 7 8 9 10 11 12
| class Resource(): def __enter__(self): print('===connect to resource===') return self def __exit__(self, exc_type, exc_val, exc_tb): print('===close resource connection===') return True def operate(self): 1/0
with Resource() as res: res.operate()
|
exc_type
异常类型,exc_val
异常值,exc_tb
异常栈信息
禁止对象被深拷贝
重写类的__deepcopy__
和__copy__
方法,使之返回self
,就可以禁止对象被深拷贝,本质是deepcopy
是调用类的__deepcopy__
方法。
集合中某一个满足条件和全部满足条件
1 2
| any(condition(item) for item in items) all(condition(item) for item in items)
|