同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
Multiple-Target Assignments
A multiple-target assignment simply assigns all the given names to the object all the way to the right. The following, for example, assigns the three variables a, b, and c to the string 'spam':
>>> a = b = c = 'spam'
>>> a, b, c
('spam', 'spam', 'spam')
This form is equivalent to (but easier to code than) these three assignments:
>>> c = 'spam'
>>> b = c
>>> a = b
Multiple-target assignment and shared references
Keep in mind that there is just one object here, shared by all three variables (they all wind up pointing to the same object in memory). This behavior is fine for immutable types—for example, when initializing a set of counters to zero (recall that variables must be assigned before they can be used in Python, so you must initialize counters to zero before you can start adding to them):
>>> a = b = 0
>>> b = b + 1
>>> a, b
(0, 1)
Here, changing b only changes b because numbers do not support in-place changes. As long as the object assigned is immutable, it’s irrelevant if more than one name references it.
As usual, though, we have to be more cautious when initializing variables to an empty mutable object such as a list or dictionary:
>>> a = b = []
>>> b.append(42)
>>> a, b
([42], [42])
This time, because a and b reference the same object, appending to it in-place through b will impact what we see through a as well. This is really just another example of the shared reference phenomenon we first met in Chapter 6. To avoid the issue, initialize mutable objects in separate statements instead, so that each creates a distinct empty object by running a distinct literal expression:
>>> a = []
>>> b = []
>>> b.append(42)
>>> a, b
([], [42])
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏