官术网_书友最值得收藏!

References to mutable objects

Python objects show this name-binding behavior for all types. The assignment operator only ever binds object to names, it never copies an object by value. To help make this point crystal clear, let's look at another example using mutable objects: Lists. Unlike the immutable ints that we just looked at, list objects have mutable state, meaning that the value of a list object can change over time.

To illustrate this, we first create an list object with three elements, binding the list object to a reference named r:

>>> r = [2, 4, 6]
>>> r
[2, 4, 6]

We then assign the reference r to a new reference s:

>>> s = r
>>> s
[2, 4, 6]

The reference-object diagram for this situation makes it clear that we have two names referring to a single list instance:

Figure 4.9: 's' and 'r' refer to the same list object

When we modify the list referred to by s by changing the middle element, we see that the list referred to by r has changed as well:

>>> s[1] = 17
>>> s
[2, 17, 6]
>>> r
[2, 17, 6]

Again, this is because the names s and r refer to the same mutable object , a fact that we can verify by using the is keyword which we learned about earlier:

>>> s is r
True

The main point of this discussion is that Python doesn't really have variables in the metaphorical sense of a box holding a value. It only has named references to objects, and these references behave more like labels which allow us to retrieve objects. That said, it's still common to talk about variables in Python because it's convenient. We will continue to do so throughout this book, secure in the knowledge that you now understand what's really going on behind the scenes.

主站蜘蛛池模板: 二手房| 昌平区| 胶州市| 竹北市| 乌鲁木齐县| 达孜县| 顺平县| 辉南县| 金乡县| 兴和县| 禄劝| 兰溪市| 凭祥市| 陆川县| 西华县| 苍南县| 仁怀市| 大关县| 阿坝县| 英超| 定日县| 西平县| 贵溪市| 武邑县| 策勒县| 云南省| 永仁县| 江永县| 昌黎县| 福泉市| 安庆市| 双桥区| 五原县| 樟树市| 饶平县| 克东县| 报价| 福州市| 楚雄市| 土默特左旗| 金乡县|