这篇文章的灵感来自于一个新项目AshortguideonfeaturesofPython3fordatascientists,其中列出了作者在Python3中使用的一些特性。正好我也想写一篇介绍Python3(特别是Python3.6+)独特用法的文章。开始吧!pathlib模块pathlib模块是Python3中的一个新模块,可以让你更方便的处理路径相关的工作。in:frompathlibimportPathIn:Path.home()Out:PosixPath('/Users/dongweiming')#用户目录In:path=Path('/user')In:path/'local'#很直观Out:PosixPath('/user/local')In:str(path/'local'/'bin')Out:'/user/local/bin'In:f=Path('example.txt')In:f.write_bytes('Thisisthecontent'.encode('utf-8'))Out[16]:19In:withf.open('r',encoding='utf-8')ashandle:#open现在是方法....:print('readfromopen():{!r}'.format(handle.read())).....:readfromopen():'Thisisthecontent'In:p=Path('touched')In:p.exists()#integratedMultiple常用方法Out:FalseIn:p.touch()In:p.exists()Out:TrueIn:p.with_suffix('.jpg')Out:PosixPath('touched.jpg')In:p.is_dir()Out:falseIn:p.joinpath('a','b')Out:PosixPath('touched/a/b')可迭代对象的拆包in:a,b,*rest=range(10)#学过Lisp很容易理解,它等同于一个"everythingelse"In:aOut:0In:bOut:1In:restOut:[2,3,4,5,6,7,8,9]In:*prev,next_to_last,last=range(10)In:prev,next_to_last,lastOut:([0,1,2,3,4,5,6,7],8,9)强制关键字参数使用mandatorykeywordarguments比使用positionalarguments更高效意思更明确,程序可读性更强,所以可以强制这些参数使用关键字参数来传递,将强制关键字参数放在某个参数后面可以达到这种效果或单个:In:defrecv(maxsize,*,block):....:......:pass.....:In:recv(1024,True)--------------------------------------------------------------------------TypeErrorTraceback(mostrecentcallast)
