(python learn) 2 variable

The variable python can be writen with number, underline, and characters. The number can not be in the first position of the variable name. 

In python, the variable is like a pointer pointing to a memory area where holding the value. It is not like the variable in c/c++. In c/c++ the variable is an memory area holding a value. So you need to decalre the variable first, then os will preserve some memory space based on the variable type. But in python, you dont need to declare it first. When you assign value to the variable, the vairable will poing to a position where holding the value. 

For example:

[root@racnode1 test]# python
Python 2.6.6 (r266:84292, Dec  7 2011, 20:48:22)
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>
>>>
>>> v1=8
>>> v2=0
>>> v3=8
>>> v1+v2
8
>>>

As you can see above. We have three varibales and we didnt declare them first.  

As we said earily, the variable is a pointer pointing to a memory space holding a value. In our case the v1=8 v3=8 should all pointing to a space which holding the number 8, right? Let`s check.

>>> id(v1)
29479568
>>> id(v2)
29479760
>>> id(v3)
29479568
>>>

The id() function can tell the memory address which pointing by the variable.

Yes, they all pointing to one position. That the the special place in python. If in c/c++, the v1 and v3 will be stand for different memory area.

 Anothere way to show the special feature 

>>> id(v1)
29479568
>>> id(v2)
29479760
>>> id(v3)
29479568
>>>
>>> v1=0
>>> id(v1)
29479760

We changed the v1=0 so v1 and v2 have the same value. If it is in c/c++, the memory area for v1 will not change. Just the values changed. But we can see in python that the memory area is changed.

原文地址:https://www.cnblogs.com/kramer/p/2915801.html