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()

执行结果如下:

转载于:https://my.oschina.net/u/3472227/blog/1036755

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值