资源描述:
《Dive Into Python 3, r867 (2010)》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、CHAPTER-1.WHAT’SNEWIN“DIVEINTOPYTHON3”❝Isn’tthiswherewecamein?❞—PinkFloyd,TheWall-1.1.A.K.A.“THEMINUSLEVEL”AreyoualreadyaPythonprogrammer?Didyoureadtheoriginal“DiveIntoPython”,ormaybeevenbuyitonpaper?(Thanks!)AreyoureadytotaketheplungeintoPython3?…Ifso,readon.(Ifnoneofthatistrue,you’dbebetteroffstar
2、tingatthebeginning.)Python3comeswithascriptcalled2to3.Learnit.Loveit.Useit.PortingCodetoPython3with2to3isareferenceofallthethingsthatthe2to3toolcanfixautomatically.Sincealotofthosethingsaresyntaxchanges,it’sagoodstartingpointtolearnaboutalotofthesyntaxchangesinPython3.(printisnowafunction,`x`doesn’t
3、work,&c.)CaseStudy:PortingchardettoPython3documentsmy(ultimatelysuccessful)efforttoportanon-triviallibraryfromPython2toPython3.Itmayhelpyou;itmaynot.There’safairlysteeplearningcurve,sinceyouneedtokindofunderstandthelibraryfirst,soyoucanunderstandwhyitbrokeandhowIfixedit.Alotofthebreakagecentersaroun
4、dstrings.Speakingofwhich…Strings.Whew.Wheretostart.Python2had“strings”and“Unicodestrings.”Python3has“bytes”and“strings.”Thatis,allstringsarenowUnicodestrings,andifyouwanttodealwithabagofbytes,youusethenewbytestype.Python3willneverimplicitlyconvertbetweenstringsandbytes,soifyou’renotsurewhichoneyouha
5、veatanygivenmoment,yourcodewillalmostcertainlybreak.ReadtheStringschapterformoredetails.Bytesvs.stringscomesupagainandagainthroughoutthebook.1•InFiles,you’lllearnthedifferencebetweenreadingfilesin“binary”and“text”mode.Reading(andwriting!)filesintextmoderequiresanencodingparameter.Sometextfilemethods
6、countcharacters,butothermethodscountbytes.Ifyourcodeassumesthatonecharacter==onebyte,itwillbreakonmulti-bytecharacters.•InHTTPWebServices,thehttplib2modulefetchesheadersanddataoverHTTP.HTTPheadersarereturnedasstrings,buttheHTTPbodyisreturnedasbytes.•InSerializingPythonObjects,you’lllearnwhythepickle
7、moduleinPython3definesanewdataformatthatisbackwardlyincompatiblewithPython2.(Hint:it’sbecauseofbytesandstrings.)AlsoJSON,whichdoesn’tsupportthebytestypeatall.I’llshowyouhowtohackaroundthat.•InCasestud