Python学习笔记(五)- 动态类型间奏(The Dynamic Typing Interlude)

1.考虑下面三个语句。它们是否更改了A的值?
A = 'spam'
B = A
B = 'shrubbery'
答:没有改变,A仍然打印 'spam'。当B被赋值字符串 'shrubbery',所有发生的事是变量B被重新设置为指向新的字符串对象。A和B初始指向相同的字符串对象 'spam',但是在Python中,变量名字从来不会联系到一起(变量名之间没关系,只是引用相同对象)。因而,把B设置为不同对象对A没有影响。当最后的语句在这变为 B = B +  'shrubbery'相同的结果也会发生,顺便说一句——字符串拼接会产生新的对象结果,仅被赋给了B。我们从来不能原地更改字符串,因为字符串是不可变的(immutable)。


2.考虑下面三个语句。它们是否更改了A的值?
A = ['spam']
B = A
B[0] = 'shrubbery'

答:会改变,A现在打印出['shrubbery']。技术上讲,我们没有真正地改变任何A或者B,我们改变它们引用的对象的部分,通过变量B适时地原地覆写对象(对象是可变的【mutable】)。因为A引用B相同的对象,所以A也改变了。

 

3.那这样呢?A的值改变了么?
A = ['spam']
B = A[:]
B[0] = 'shrubbery'
答:没有改变,A仍然打印['spam']。第三句通过B适时地原地赋值语句没有起效果,因为在赋给B之前,切片表达式复制了对象。在第二个赋值语句中,有两个有相同值的不同对象(在Python中,我们说它们不相等 ==【值是否相等】,但不相同 is 【对象是否相同】)。第三个语句改变了B指向的列表对象的值,但不是A所指向的。

 

标注:转载《Learning Python 5th Edition》[奥莱理]
1. Consider the following three statements. Do they change the value printed for A?
    A = "spam"
    B = A
    B = "shrubbery"
2. Consider these three statements. Do they change the printed value of A?
    A = ["spam"]
    B = A
    B[0] = "shrubbery"
3. How about these—is A changed now?
    A = ["spam"]
    B = A[:]
    B[0] = "shrubbery"

1. No: A still prints as "spam". When B is assigned to the string "shrubbery", all that happens is that the variable B is reset to point to the new string object. A and B initially share (i.e., reference/point to) the same single string object "spam", but two names are never linked together in Python. Thus, setting B to a different object has no effect on A. The same would be true if the last statement here were B = B + 'shrubbery', by the way—the concatenation would make a new object for its result, which would then be assigned to B only. We can never overwrite a string (or number, or tuple) in place, because strings are immutable.
2. Yes: A now prints as ["shrubbery"]. Technically, we haven’t really changed either A or B; instead, we’ve changed part of the object they both reference (point to) by overwriting that object in place through the variable B. Because A references the same object as B, the update is reflected in A as well.
3. No: A still prints as ["spam"]. The in-place assignment through B has no effect this time because the slice expression made a copy of the list object before it was assigned to B. After the second assignment statement, there are two different list objects that have the same value (in Python, we say they are ==, but not is). The third statement changes the value of the list object pointed to by B, but not that pointed to by A.

你可能感兴趣的:(Learning,Python,5th,Edition,Python,Learning,Python,5th,Edition,奥莱理)