python会在赋值时复制对象吗? [英] Does python copy objects on assignment?

查看:23
本文介绍了python会在赋值时复制对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到 python 中的赋值不会像在 c 中那样复制它,它为对象分配指针.

I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.

但是当我调试这个函数时:

But when I debug this function:

def popall(self):
    objs = self.curstack
    self.curstack = []
    return objs

看起来正在进行某种复制.这个函数运行后obis全是东西,self.curstack是空的……

It looks like some kind of copy is taking place. After this function runs obis is full of things and self.curstack is empty…

所以一些副本正在进行中.它是深的还是浅的?

So some copy is going on. Is it deep or shallow?

推荐答案

它不复制任何内容.只是分配给 self.curstack 不会修改任何用于引用的 self.curstack .它只是让 self.curstack 指向别的东西.

It doesn't copy anything. It's just that assigning to self.curstack does not modify whatever self.curstack used to refer to. It just makes self.curstack refer to something else.

这样想.self.curstack 指向一些东西.使用 objs = self.curstack 你让 objs 指向同样的东西.使用 self.curstack = [],您可以使 self.curstack 指向一个空列表.这不会删除 self.curstack 曾经指向的任何内容;那个东西还在那里,objs 仍然指向它.

Think of it this way. self.curstack points to some stuff. With objs = self.curstack you make objs point to that same stuff. With self.curstack = [], you make self.curstack point to an empty list. This doesn't remove any of the stuff that self.curstack used to point at; that stuff is still there and objs is still pointing at it.

这篇文章 使用标签标签的一个很好的类比来解释它.

This article explains it using a nice analogy of label tags.

这篇关于python会在赋值时复制对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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