当前位置: 首页 > 科技观察

Python3的特色用法:新特性总结

时间:2023-03-22 13:53:34 科技观察

这篇文章的灵感来自于一个新项目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)in()---->1recv(1024,True)TypeError:recv()takes1positionalargumentbut2weregivenIn:recv(1024,block=True)wildcard**我们都知道在Python2递归目录不能直接通配时,需要这样:found_images=\glob.glob('/path/*.jpg')\+glob.glob('/path/*/*.jpg')\+glob.glob('/path/*/*/*.jpg')\+glob.glob('/path/*/*/*/*.jpg')\+glob.glob('/path/*/*/*/*/*.jpg')Python3更干净:found_images=glob.glob('/path/**/*.jpg',recursive=True)事实上,更好的用法是使用pathlib:found_images=pathlib.Path('/path/').glob('**/*.jpg')print在Python3之后,print变成了一个具有更多扩展能力的函数:In:print(*[1,2,3],sep='\t')123In:[xifx%3elseprint('',x)forxinrange(10)]0369Out:[None,1,2,None,4,5,None,7,8,None]格式字符串变量In:name='Fred'In:f'Mynameis{name}'Out:'MynameisFred'In:fromdatetimeimport*In:date=datetime.now().date()In:f'{date}wasona{date:%A}'Out:'2018-01-17wasonaWednesday'In:deffoo():....:return20....:In:f'result={foo()}'Out:'result=20'更严格的比较规范以下类型的用法在Python3都是非法的:3<'3'2

最新推荐
猜你喜欢