diveintopython3 official_【python3】关于列表的copy方法的一个官方bug

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

不认同你的说法,出现这种原因在于python将int型视为不可变类型。

使用help函数可以看到,官方对字典和列表的copy方法均描述为浅复制,浅复制原理是复制了对象的地址(使用id函数可以观察)。

>>> help(dict.copy)

Help on method_descriptor:

copy(...)

D.copy() -> a shallow copy of D

>>> help(list.copy)

Help on method_descriptor:

copy(...)

L.copy() -> list -- a shallow copy of L

我们对对象中的不可变类型元素进行“修改”时,实际上是将这个元素指向了其他地址。这就是为什么你误解这段代码及其结果:

>>> a[0] = 10

>>> a

[10, 2, [3, 4]]

>>> b

[1, 2, [3, 4]]

我们使用id函数来看看其中的变化:

>>> a = [1, 2, [3, 4]]

>>> b = a.copy()

>>> [id(x) for x in a]

[1384787088, 1384787104, 49367440]

>>> [id(x) for x in b]

[1384787088, 1384787104, 49367440]

可以看到地址相同,确实实现了浅复制。

那当我们“修改”a[0]呢?

>>> a[0] = 10

>>> b

[1, 2, [3, 4]]

>>> [id(x) for x in a]

[1384787232, 1384787104, 49367440]

>>> [id(x) for x in b]

[1384787088, 1384787104, 49367440]

实际上a[0]被指向了新的地址。

现在我们创建一个变量,其值为10,再看看它的地址:

>>> c = 10

>>> id(c)

1384787232

它指向的地址与a[0]相同。现在你知道是什么问题了吗?

CHAPTER-1.WHAT’SNEWIN“DIVEINTO PYTHON3” ❝Isn’tthiswherewecamein?❞ —PinkFloyd,TheWall -1.1.A.K.A.“THEMINUSLEVEL” AreyoualreadyaPythonprogrammer?Didyoureadtheoriginal“DiveIntoPython”?Didyoubuyit onpaper?(Ifso,thanks!)AreyoureadytotaketheplungeintoPython3?…Ifso,readon.(Ifnoneofthat istrue,you’dbebetteroffstartingatthebeginning.) Python3comeswithascriptcalled2to3.Learnit.Loveit.Useit.PortingCodetoPython3with2to3isa referenceofallthethingsthatthe2to3toolcanfixautomatically.Sincealotofthosethingsaresyntax changes,it’sagoodstartingpointtolearnaboutalotofthesyntaxchangesinPython3.(printisnowa function,`x`doesn’twork,&c.) CaseStudy:PortingchardettoPython3documentsmy(ultimatelysuccessful)efforttoportanon-trivial libraryfromPython2toPython3.Itmayhelpyou;itmaynot.There’safairlysteeplearningcurve,since youneedtokindofunderstandthelibraryfirst,soyoucanunderstandwhyitbrokeandhowIfixedit.A lotofthebreakagecentersaroundstrings.Speakingofwhich… Strings.Whew.Wheretostart.Python2had“strings”and“Unicodestrings.”Python3has“bytes”and “strings.”Thatis,allstringsarenowUnicodestrings,andifyouwanttodealwithabagofbytes,youuse thenewbytestype.Python3willneverimplicitlyconvertbetweenstringsandbytes,soifyou’renotsure whichoneyouhaveatanygivenmoment,yourcodewillalmostcertainlybreak.ReadtheStringschapter formoredetails. Bytesvs.stringscomesupagainandagainthroughoutthebook. 1 •InFiles,you’lllearnthedifferencebetweenreadingfilesin“binary”and“text”mode.Reading(andwriting!) filesintextmoderequiresanencodingparameter.Sometextfilemethodscountcharacters,butother methodscountbytes.Ifyourcodeassumesthatonecharacter==onebyte,itwillbreakonmulti-byte characters. •InHTTPWebServices,thehttplib2modulefetchesheadersanddataoverHTTP.HTTPheadersare returnedasstrings,buttheHTTPbodyisreturnedasbytes. •InSerializingPythonObjects,you’lllearnwhythepicklemoduleinPython3definesanewdataformatthat isbackwardlyincompatiblewithPython2.(Hint:it’sbecauseofbytesandstrings.)AlsoJSON,whichdoesn’t supportthebytestypeatall.I’llshowyouhowtohackaroundthat. •InCasestudy:portingchardettoPython3,it’sjustabloodymessofbytesandstringseverywhere. Evenifyoudon’tcareaboutUnicode(ohbutyouwill),you’llwanttoreadaboutstringformattinginPython 3,whichiscompletelydifferentfromPython2. IteratorsareeverywhereinPython3,andIunderstandthemalotbetterthanIdidfiveyearsagowhenI wrote“DiveIntoPython”.Youneedtounderstandthemtoo,becauselotsoffunctionsthatusedtoreturn listsinPython2willnowreturniteratorsinPython3.Ataminimum,youshouldreadthesecondhalfof theIteratorschapterandthesecondhalfoftheAdvancedIteratorschapter. Bypopularrequest,I’veaddedanappendixonSpecialMethodNames,whichiskindoflikethePythondocs “DataModel”chapterbutwithmoresnark. WhenIwaswriting“DiveIntoPython”,alloftheavailableXMLlibrariessucked.ThenFredrikLundhwrote ElementTree,whichdoesn’tsuckatall.ThePythongodswiselyincorporatedElementTreeintothestandard library,andnowitformsthebasisformynewXMLchapter.TheoldwaysofparsingXMLarestillaround, butyoushouldavoidthem,becausetheysuck! AlsonewinPython—notinthelanguagebutinthecommunity—istheemergenceofcoderepositories likeThePythonPackageIndex(PyPI).Pythoncomeswithutilitiestopackageyourcodeinstandardformats anddistributethosepackagesonPyPI.ReadPackagingPythonLibrariesfordetails.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值