摘要:Python 奇技淫巧 顯示有限的接口到外部 當(dāng)發(fā)布python第三方package時(shí),并不希望代碼中所有的函數(shù)或者class可以被外部import撒璧,在__init__.py中添加__all__屬性吠冤,該list中填寫可以import的類或者函數(shù)名雕沉, 可以起到限制的import的作用芭届, 防止外部import其他函數(shù)或者類蛔钙。
顯示有限的接口到外部
當(dāng)發(fā)布python第三方package時(shí)锌云,并不希望代碼中所有的函數(shù)或者class可以被外部import,在__init__.py中添加__all__屬性夸楣,該list中填寫可以import的類或者函數(shù)名宾抓, 可以起到限制的import的作用, 防止外部import其他函數(shù)或者類豫喧。
#!/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語句需要支持上下文管理協(xié)議的對(duì)象石洗,上下文管理協(xié)議包含__enter__和__exit__兩個(gè)方法。 with語句建立運(yùn)行時(shí)上下文需要通過這兩個(gè)方法執(zhí)行進(jìn)入和退出操作紧显。
其中上下文表達(dá)式是跟在with之后的表達(dá)式讲衫, 該表達(dá)式返回一個(gè)上下文管理對(duì)象。
#常見with使用場景
withopen("test.txt","r")asmy_file:#注意,是__enter__()方法的返回值賦值給了my_file,
forlineinmy_file:
printline
詳細(xì)原理可以查看這篇文章孵班,淺談 Python 的 with 語句涉兽。
知道具體原理,我們可以自定義支持上下文管理協(xié)議的類篙程,類中實(shí)現(xiàn)__enter__和__exit__方法枷畏。
#!/usr/bin/envpython
#-*-coding:utf-8-*-
classMyWith(object):
def__init__(self):
print"__init__ method"
def__enter__(self):
print"__enter__ method"
returnself#返回對(duì)象給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()
執(zhí)行結(jié)果如下:
__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
證明了會(huì)先執(zhí)行__enter__方法, 然后調(diào)用with內(nèi)的邏輯, 最后執(zhí)行__exit__做退出處理, 并且, 即使出現(xiàn)異常也能正常退出