资源描述:
《Dive Into Python 3, r870 (2010)》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、CHAPTER-1.WHAT’SNEWIN“DIVEINTOPYTHON3”❝Isn’tthiswherewecamein?❞—PinkFloyd,TheWall-1.1.A.K.A.“THEMINUSLEVEL”AreyoualreadyaPythonprogrammer?Didyoureadtheoriginal“DiveIntoPython”?Didyoubuyitonpaper?(Ifso,thanks!)AreyoureadytotaketheplungeintoPython3?…Ifso,readon.(Ifnoneofthatistrue,you’d
2、bebetteroffstartingatthebeginning.)Python3comeswithascriptcalled2to3.Learnit.Loveit.Useit.PortingCodetoPython3with2to3isareferenceofallthethingsthatthe2to3toolcanfixautomatically.Sincealotofthosethingsaresyntaxchanges,it’sagoodstartingpointtolearnaboutalotofthesyntaxchangesinPython3.(
3、printisnowafunction,`x`doesn’twork,&c.)CaseStudy:PortingchardettoPython3documentsmy(ultimatelysuccessful)efforttoportanon-triviallibraryfromPython2toPython3.Itmayhelpyou;itmaynot.There’safairlysteeplearningcurve,sinceyouneedtokindofunderstandthelibraryfirst,soyoucanunderstandwhyitbrok
4、eandhowIfixedit.Alotofthebreakagecentersaroundstrings.Speakingofwhich…Strings.Whew.Wheretostart.Python2had“strings”and“Unicodestrings.”Python3has“bytes”and“strings.”Thatis,allstringsarenowUnicodestrings,andifyouwanttodealwithabagofbytes,youusethenewbytestype.Python3willneverimplicitly
5、convertbetweenstringsandbytes,soifyou’renotsurewhichoneyouhaveatanygivenmoment,yourcodewillalmostcertainlybreak.ReadtheStringschapterformoredetails.Bytesvs.stringscomesupagainandagainthroughoutthebook.1•InFiles,you’lllearnthedifferencebetweenreadingfilesin“binary”and“text”mode.Reading
6、(andwriting!)filesintextmoderequiresanencodingparameter.Sometextfilemethodscountcharacters,butothermethodscountbytes.Ifyourcodeassumesthatonecharacter==onebyte,itwillbreakonmulti-bytecharacters.•InHTTPWebServices,thehttplib2modulefetchesheadersanddataoverHTTP.HTTPheadersarereturnedass
7、trings,buttheHTTPbodyisreturnedasbytes.•InSerializingPythonObjects,you’lllearnwhythepicklemoduleinPython3definesanewdataformatthatisbackwardlyincompatiblewithPython2.(Hint:it’sbecauseofbytesandstrings.)AlsoJSON,whichdoesn’tsupportthebytestypeatall.I’llshowyouhowtohackaroundthat.•InCas
8、estud