【发布时间】:2015-01-30 02:53:54
【问题描述】:
我正在尝试为自己澄清 Python 的“分配”值规则 到变量。
以下 Python 和 C++ 的比较是否有效?
在 C/C++ 中,
int a=7语句的意思是,内存分配给一个名为a的整数变量(=符号的 LEFT 上的数量) 然后才将值 7 存储在其中。在 Python 中,语句
a=7的意思是,一个值为 7 的 无名 整数对象(=的 RIGHT 侧的数量)是首先创建并存储在内存中的某个位置。那么名称a就绑定到这个对象了。
以下 C++ 和 Python 程序的输出似乎证实了这一点,但我希望得到一些反馈,我是否正确。
C++ 为a 和b 生成不同的内存位置
而a 和b 似乎指的是Python 中的相同位置
(通过 id() 函数的输出)
C++ 代码
#include<iostream>
using namespace std;
int main(void)
{
int a = 7;
int b = a;
cout << &a << " " << &b << endl; // a and b point to different locations in memory
return 0;
}
输出:0x7ffff843ecb8 0x7ffff843ecbc
Python:代码
a = 7
b = a
print id(a), ' ' , id(b) # a and b seem to refer to the same location
输出:23093448 23093448
【问题讨论】:
-
您可能会觉得这很有帮助:Facts and Myths about Python names and values.
-
@unutbu 这是一个很棒的链接。非常感谢!