Python 奇技淫巧

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

显示有限的接口到外部

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

#!/usr/bin/envpython

#-*-coding:utf-8-*-

frombaseimportAPIBase

fromclientimportClient

fromdecoratorimportinterface,export,stream

fromserverimportServer

fromstorageimportStorage

fromutilimport(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使用场景

withopen("test.txt","r")asmy_file:#注意,是__enter__()方法的返回值赋值给了my_file,

forlineinmy_file:

printline

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

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

#!/usr/bin/envpython

#-*-coding:utf-8-*-

classMyWith(object):

def__init__(self):

print"__init__ method"

def__enter__(self):

print"__enter__ method"

returnself#返回对象给as后的变量

def__exit__(self,exc_type,exc_value,exc_traceback):

print"__exit__ method"

ifexc_tracebackisNone:

print"Exited without Exception"

returnTrue

else:

print"Exited with Exception"

returnFalse

deftest_with():

withMyWith()asmy_with:

print"running my_with"

print"------分割线-----"

withMyWith()asmy_with:

print"running before Exception"

raiseException

print"running after Exception"

if__name__=='__main__':

test_with()

执行结果如下:

__init__ method

__enter__ method

running my_with

__exit__ method

ExitedwithoutException

------分割线-----

__init__ method

__enter__ method

running beforeException

__exit__ method

ExitedwithException

Traceback(most recent calllast):

File"bin/python",line34,in

exec(compile(__file__f.read(),__file__,"exec"))

File"test_with.py",line33,in

test_with()

File"test_with.py",line28,intest_with

raiseException

Exception

证明了会先执行__enter__方法, 然后调用with内的逻辑, 最后执行__exit__做退出处理, 并且, 即使出现异常也能正常退出


原文链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作者:Andrew Liu原文地址:Python奇技淫巧 显示有限的接口到外部 当发布python第三方packa...
    IT程序狮阅读 6,502评论 0 23
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,477评论 19 139
  • 显示有限的接口到外部 当发布python第三方package时, 并不希望代码中所有的函数或者class可以被外部...
    种花家LY阅读 2,895评论 0 0
  • 转载自:http://mp.weixin.qq.com/s/LO1yyFeUA6pR_YPyfDoSig 姓名:梅...
    虐先森阅读 5,262评论 0 1
  • 版权归作者所有,任何形式转载请联系作者。 作者:我爱old先 来源:https://book.douban.com...
    斯坦威阅读 3,359评论 0 0