当你在 Python 中将一个变量的值赋给另一个变量时会发生什么? [英] What happens when you assign the value of one variable to another variable in Python?

查看:96
本文介绍了当你在 Python 中将一个变量的值赋给另一个变量时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我学习python的第二天(我知道C++的基础知识和一些OOP.),我对python中的变量有些困惑.

以下是我目前对它们的理解:

Python 变量是对对象(可变或不可变)的引用(或指针?).当我们有类似 num = 5 的东西时,不可变对象 5 在内存中的某处被创建,并且名称-对象引用对 num 被创建在某个命名空间中.当我们有 a = num 时,什么都没有被复制,但现在两个变量都指向同一个对象,并且 a 被添加到同一个命名空间.

这就是我的书,用 Python 自动化无聊的东西,让我感到困惑的地方.由于是新手书,没有提到对象、命名空间等,尝试解释如下代码:

<预><代码>>>>垃圾邮件 = 42>>>奶酪 = 垃圾邮件>>>垃圾邮件 = 100>>>垃圾邮件100>>>起司42

它提供的解释与一本 C++ 书籍的解释完全相同,我对此并不满意,因为我们正在处理对象的引用/指针.所以在这种情况下,我猜在第三行,由于整数是不可变的,spam 被分配了一个全新的指针/引用到内存中的不同位置,即它最初指向的内存to 没有被修改.因此,我们有 cheese 引用由 spam 引用的初始对象.这是正确的解释吗?

解决方案

作为 C++ 开发人员,您可以将 Python 变量视为指针.

因此,当您编写 spam = 100 时,这意味着您分配了之前指向对象 42 的指针",以指向对象 <代码>100.

之前,cheese 被指定为指向与spam 指向的对象相同的对象,当时正好是42.由于你没有修改cheese,它仍然指向42.

在这种情况下,不变性与它无关,因为指针赋值不会改变所指向对象的任何内容.

This is my second day of learning python (I know the basics of C++ and some OOP.), and I have some slight confusion regarding variables in python.

Here is how I understand them currently:

Python variables are references (or pointers?) to objects (which are either mutable or immutable). When we have something like num = 5, the immutable object 5 is created somewhere in memory, and the name-object reference pair num is created in a certain namespace. When we have a = num, nothing is being copied, but now both variables refer to the same object and a is added to the same namespace.

This is where my book, Automate the boring stuff with Python, confuses me. As it's a newbie book, it doesn't mention objects, namespaces, etc., and it attempts to explain the following code:

>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> cheese
42

The explanation it offers is exactly the same as that of a C++ book, which I am not happy about as we are dealing with references/pointers to objects. So in this case, I guess that in the 3rd line, as integers are immutable, spam is being assigned an entirely new pointer/reference to a different location in memory, i.e. the memory that it was initially pointing to wasn't modified. Hence we have cheese referring to the initial object referred to by spam. Is this the correct explanation?

解决方案

As a C++ developer you can think of Python variables as pointers.

Thus when you write spam = 100, this means that you "assign the pointer", which was previously pointing to the object 42, to point to the object 100.

Earlier on, cheese was assigned to point to the same object as spam pointed to, which happened to be 42 at that time. Since you have not modified cheese, it still points to 42.

Immutability has nothing to do with it in this case, since pointer assignment does not change anything about the object being pointed to.

这篇关于当你在 Python 中将一个变量的值赋给另一个变量时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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