人人社区!

python的变量是指向一个对象吗?比如是数字10

In Python, a variable is not exactly a pointer to an object, but rather a name bound to an object. This is known as "name binding" or "symbolic reference".

When you assign a value to a variable, such as x = 10, what happens is that the variable x is bound to the object 10, which is an integer object. This binding is a connection between the name x and the object 10.

In other words, x is not a pointer to the memory location where the object 10 is stored. Instead, x is a name that refers to the object 10. The object 10 is a separate entity that exists independently of the variable x.

Here's a key difference:

  • In languages like C or C++, a pointer is a memory address that directly references a location in memory. Changing the value at that memory location affects all references to that location.

  • In Python, modifying the object 10 does not affect the variable x itself. The variable x remains bound to the same object 10.

For example:

x = 10
y = x
x += 1
print(y)  # still prints 10

As you can see, changing the value of x does not affect the value of y, because y is also bound to the original object 10.

So, in summary, in Python, a variable is a name bound to an object, not a pointer to an object. This distinction can be important when working with Python, especially when dealing with mutable objects or object references. 💡


回复

Python id() 函数

Python 内置函数 Python 内置函数


描述

id() 函数返回对象的唯一标识符,标识符是一个整数。


CPython 中 id() 函数用于获取对象的内存地址。


语法

id 语法:


id([object])

参数说明:


object -- 对象。

返回值

返回对象的内存地址。



回复
回复 楼主
顶部