显示有限的接口到外部
#!/usr/bin/env python# -*- coding: utf-8 -*-from base import APIBasefrom client import Clientfrom decorator import interface, export, streamfrom server import Serverfrom storage import Storagefrom util import (LogFormatter, disable_logging_to_stderr,enable_logging_to_kids, info)__all__ = ['APIBase', 'Client', 'LogFormatter', 'Server','Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids','export', 'info', 'interface', 'stream']
with的魔力
with语句需要支持上下文管理协议的对象, 上下文管理协议包含__enter__和__exit__两个方法。 with语句建立运行时上下文需要通过这两个方法执行进入和退出操作。
其中上下文表达式是跟在with之后的表达式, 该表达式返回一个上下文管理对象。
# 常见with使用场景with open("test.txt", "r") as my_file: # 注意, 是__enter__()方法的返回值赋值给了my_file,for line in my_file:print line
详细原理可以查看这篇文章, 浅谈 Python 的 with 语句。
知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__enter__和__exit__方法。
#!/usr/bin/env python# -*- coding: utf-8 -*-class MyWith(object):def __init__(self):print "__init__ method"def __enter__(self):print "__enter__ method"return self # 返回对象给as后的变量def __exit__(self, exc_type, exc_value, exc_traceback):print "__exit__ method"if exc_traceback is None:print "Exited without Exception"return Trueelse:print "Exited with Exception"return Falsedef test_with():with MyWith() as my_with:print "running my_with"print "------分割线-----"with MyWith() as my_with:print "running before Exception"raise Exceptionprint "running after Exception"if __name__ == '__main__':test_with()

447

被折叠的 条评论
为什么被折叠?



