python in C language assignment and assignment operator in the huge difference

 

First, let us look at a simple C program:

1 a = 8;
2 b = a;
3 b = 6;
4 printf("a = %d, b = %d\n",  a, b);
View Code

 

I believe as long as learned C language, do not know the program will run the program will be able to print out a = 8, b = 6.

Now let's take a look at this program python version

1 a = 8
2 b = a
3 b = 6
4 print(a, b)
View Code


Let's look at the results:

 

 

Everything seems normal.

 

No, if really so simple, it is up to me why! ! !

 

Look, the program again. . .

1 name = ['fujian', 'beijing', 'shanghai']
2 name2 = name
3 name2[1] = 'tainjing'
4 print(name)
5 print(name2)
python program


The result is still not what we thought it would:

[ 'Fujian', 'beijing', 'shanghai']

[ 'Fujian', 'tainjing', 'shanghai']

 

The reality is:

 

 

 Why!Why!Why!

 

For the following reasons:

  1. c language variable is like a box, a = 8 8 like the case of this data into the named a; and the python in this respect can be regarded as a big difference with the C language;

    python variables is somewhat similar to the C language pointer, a = 8 in python like a data point to this 8.

  2. python in each assignment is the variable to point to a new data (position)

 

Now we come back to take a look at these two python programs,

  One:

      a = 8

      b = a

      b = 6

  首先语句a = 8说明变量a指向了8这个数据;

  接着语句a = b说明变量b指向了a,也就等同与a与b一起指向了8这个数据;

  最后语句b = 6,说明此时变量b的指向已经发生了改变, 但是变量a的指向并没有改变,变量b现在指向了6这个数据,变量a还是指向原来的数据8;

  所以最后会打印出a = 8,  b = 6.

 

 

  二:

    name = ["fujian", "beijing", "shanghai"]

    name2 = name

    name2[1] = "tianjing"

     

    同样我们可以类似上一个程序那样分析:

    首先第一条语句说明变量name指向了一个列表;

    第二条语句说明变量name2与name指向了同一个列表;

    第三条语句的分析非常重要:   

    请注意

    name[1]其实也可以看成是一个‘变量’,只不过这个变量是属于name所指向的列表的一部分,它原先是指向“beijing”这个字符串,

    现在经过第三条语句后,变量name[1]就改变了指向,指向了“tianjing"这个字符串了;这样也恰好改变了列表中的内容。

    再加上最终name与name2还是指向最初的那个列表(只不过这个列表‘更新’了),

    所以现在问题不就解决了!!!

 

 

    如果您发现以上信息有问题,请及时留言,谢谢!

 

  

 

Guess you like

Origin www.cnblogs.com/ReturnOfTheKing/p/11299977.html