Python学习基础教程(learning Python)--2.2.1 Python下的变量解析

时间:2023-03-09 01:47:39
Python学习基础教程(learning Python)--2.2.1 Python下的变量解析

前文提及过变量代表内存里的某个数据,这个说法有根据么?

这里我们介绍一个python内建(built-in)函数id。我们先看看id函数的帮助文档吧。在python查某个函数的帮助文档很简单,只用help(xxx)即可。

  1. >>> help(id)

我们使用help查询一下id函数的具体信息如下:

  1. Help on built-in function id in module __builtin__:
  2. id(...)
  3. id(object) -> integer
  4. Return the identity of an object.  This is guaranteed to be unique among
  5. simultaneously existing objects.  (Hint: it's the object's memory address.)
  6. (END)

从id的帮助文档里可以看出id函数返回值就是id参数object在内存里的地址。

问题又来了,内存里有重复数据么?

  1. >>> x = 5
  2. >>> x
  3. 5
  4. >>> y = 5
  5. >>> y
  6. 5

此代码里的2个5是分别存储还是只存储一个5呢?我们用id函数来看一看,分析一下。

  1. >>> x = 5
  2. >>> y = 5
  3. >>> x
  4. 5
  5. >>> y
  6. 5
  7. >>> id(x)
  8. 163705520
  9. >>> id(y)
  10. 163705520
  11. >>> y = 6
  12. >>> id(y)
  13. 153928356

从id返回值来看,前两个返回值是相等的,那我们可以总结一下,在Python里变量“指向”某块内存,这和C语言一样!当y又被赋值其他值的时候,y的id发生了变化,由此可以证明“Python变量指向内存说”的说法正确性!

Python学习基础教程(learning Python)--2.2.1 Python下的变量解析

智普教育Python www.jeapedu.com

———————————————————————————————————