- The Python Apprentice
- Robert Smallshire Austin Bingham
- 231字
- 2021-07-02 22:17:03
Mutating without mutating
Even operations which seem naturally mutating in nature are not necessarily so. Consider the augmented assignment operator:
>>> t = 5
>>> id(t)
4297261280
>>> t += 2
>>> id(t)
4297261344
At first glance, it appears that we're asking Python to increment the integer value t by two. But the id() results here clearly show that t refers to two different objects before and after the augmented assignment.
Rather than modifying integer objects, here's a depiction of what's actually happening. Initially, we have the name t referring to an int(5) object:

Next, to perform the augmented assignment of 2 to t, Python create an int(2) object behind the scenes. Note that we never have a named reference to this object; it's managed completely by Python on our behalf:

Python then performs the addition operation between t and the anonymous int(2) giving us — you guessed it! — another integer object, this time an int(7):
Finally, Python's augmented assignment operator simply reassigns the name t to
the new int(7) object, leaving the other integer objects to be handled by the garbage collector:

- DevOps:軟件架構(gòu)師行動指南
- 測試驅(qū)動開發(fā):入門、實(shí)戰(zhàn)與進(jìn)階
- Java 9 Concurrency Cookbook(Second Edition)
- Python從小白到大牛
- Visual Basic程序設(shè)計(jì)教程
- Machine Learning with R Cookbook(Second Edition)
- Learning C++ Functional Programming
- Apache Hive Essentials
- Learning Python Design Patterns
- MATLAB 2020從入門到精通
- 學(xué)習(xí)OpenCV 4:基于Python的算法實(shí)戰(zhàn)
- Java Web開發(fā)詳解
- 零基礎(chǔ)學(xué)C語言程序設(shè)計(jì)
- INSTANT Apache ServiceMix How-to
- MongoDB Cookbook(Second Edition)