Python 奇技淫巧

摘要: Python 奇技淫巧 显示有限的接口到外部 当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init__.py中添加__all__属性,该list中填写可以import的类或者函数名, 可以起到限制的import的作用, 防止外部import其他函数或者类。

显示有限的接口到外部

当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init__.py中添加__all__属性,该list中填写可以import的类或者函数名, 可以起到限制的import的作用, 防止外部import其他函数或者类。

 
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from base import APIBase
  4. from client import Client
  5. from decorator import interface, export, stream
  6. from server import Server
  7. from storage import Storage
  8. from util import (LogFormatter, disable_logging_to_stderr,
  9. enable_logging_to_kids, info)
  10. __all__ = ['APIBase', 'Client', 'LogFormatter', 'Server',
  11. 'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids',
  12. 'export', 'info', 'interface', 'stream']

with的魔力

with语句需要支持上下文管理协议的对象, 上下文管理协议包含__enter____exit__两个方法。 with语句建立运行时上下文需要通过这两个方法执行进入和退出操作。

其中上下文表达式是跟在with之后的表达式, 该表达式返回一个上下文管理对象。

 
  1. # 常见with使用场景
  2. with open("test.txt", "r") as my_file: # 注意, 是__enter__()方法的返回值赋值给了my_file,
  3. for line in my_file:
  4. print line

详细原理可以查看这篇文章, 浅谈 Python 的 with 语句。

知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__enter____exit__方法。

 
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. class MyWith(object):
  4. def __init__(self):
  5. print "__init__ method"
  6. def __enter__(self):
  7. print "__enter__ method"
  8. return self # 返回对象给as后的变量
  9. def __exit__(self, exc_type, exc_value, exc_traceback):
  10. print "__exit__ method"
  11. if exc_traceback is None:
  12. print "Exited without Exception"
  13. return True
  14. else:
  15. print "Exited with Exception"
  16. return False
  17. def test_with():
  18. with MyWith() as my_with:
  19. print "running my_with"
  20. print "------分割线-----"
  21. with MyWith() as my_with:
  22. print "running before Exception"
  23. raise Exception
  24. print "running after Exception"
  25. if __name__ == '__main__':
  26. test_with()

执行结果如下:

​​​​​​​

原文链接

猜你喜欢

转载自3554661963.iteye.com/blog/2381691