List vs. int 赋值——“每个变量都是一个指针" [英] List vs. int assignment - "Every variable is a pointer"

查看:57
本文介绍了List vs. int 赋值——“每个变量都是一个指针"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个非常基本的问题,但我需要帮助来理解这个简短的概念.

I know it's a very basic question, but I need help understanding this short concept.

我正在学习 Python,书中说Python 中的每个变量都是一个指向对象的指针.因此,当您编写诸如 y=x 之类的东西时,您实际上是在使它们都指向同一个对象.如果你改变原始对象,你将改变指向它的所有其他指针"

I'm studying Python, and the book says "Every variable in Python is a pointer to an object. so when you write something like y=x you are infact making both of them point to the same object. If you change the original object, you will change every other pointer that points to it"

然后他们举了一个例子:

And then they give an example:

x=[1,2,3]
y=x
x[1]=3
print y

它确实打印了 [1,3,3]

然而,当我写了以下代码时:

However, when I wrote the following code:

x=5
y=x
x=7
print y

它不打印 7.它打印 5.

It does not print 7. It prints 5.

为什么?

推荐答案

你的第一个例子可以解释如下:

Your first example can be explained as follows:

x=[1,2,3]  # The name x is assigned to the list object [1,2,3]
y=x        # The name y is assigned to the same list object referenced by x
x[1]=3     # This *modifies* the list object referenced by both x and y
print y    # The modified list object is printed

然而,第二个示例仅将名称 x 重新分配给不同的整数对象:

The second example however only reassigns the name x to a different integer object:

x=5      # The name x is assigned to the integer object 5
y=x      # The name y is assigned to the same integer object referenced by x
x=7      # The name x is *reassigned* to the new integer object 7
print y  # This prints 5 because the value of y was never changed

这是关于Python 中的赋值的参考.

这篇关于List vs. int 赋值——“每个变量都是一个指针"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆