[面试题分析] Python 里面如何拷贝一个对象?(赋值,浅拷贝,深拷贝的区别)

2020-05-13 14:53:22 +08:00
 julyedu

解析:

赋值(=),就是创建了对象的一个新的引用,修改其中任意一个变量都会影响到另一个。

浅拷贝:创建一个新的对象,但它包含的是对原始对象中包含项的引用(如果用引用的方式修改其中一个对象,另外一个也会修改改变){1,完全切片方法; 2,工厂函数,如 list(); 3,copy 模块的 copy()函数}

深拷贝:创建一个新的对象,并且递归的复制它所包含的对象(修改其中一个,另外一个不会改变){copy 模块的 deep.deepcopy()函数}

顺便问下大家,现在 V2EX 的兄弟们还有需要 python 课程的吗,我可以免费送大家一些优质课程,绝对免费!

2047 次点击
所在节点    推广
15 条回复
jmc891205
2020-05-13 18:02:04 +08:00
a = 1
b = a
这算赋值、浅拷贝还是深拷贝
lxd152
2020-05-13 18:16:17 +08:00
@jmc891205 b 指向 a 的内存,算浅拷贝。
Vegetable
2020-05-13 18:34:08 +08:00
你们两个给我整楞了,一楼大哥是考教还是真问啊。
python 里数字本身是不可变对象,并不存在 shallow copy 和 deep copy 的区别,一旦区分深浅,那必然是复合对象。
kkk330
2020-05-13 18:59:30 +08:00
别忘了小整数池
jhdxr
2020-05-13 19:34:12 +08:00
@lxd152 先不说一楼这个例子是数字。。。就你单纯这描述『 b 指向 a 的内存』这明显也是赋值(按照正文中的三种分类方式)啊。。。
lxd152
2020-05-13 20:03:07 +08:00
@jhdxr 啊。。我说错了嘛。。
lxd152
2020-05-13 20:04:46 +08:00
@jhdxr
>>> a = 1
>>> b = a
>>> id(a)
140725512607392
>>> id(b)
140725512607392
youngce
2020-05-13 20:11:12 +08:00
@lxd152 #7


```
>>> a= 1
>>> b=a
>>> a=2
>>> b
1
>>> a=[1,2]
>>> c=[1,2]
>>> d = c
>>> c.append(3)
>>> c
[1, 2, 3]
>>> d
[1, 2, 3]

```
lxd152
2020-05-13 20:34:29 +08:00
@youngce 明白了。。感谢,我再多看看。
jmc891205
2020-05-13 20:44:06 +08:00
@Vegetable 哈哈 毕竟 python 里万物皆 object 嘛
qiaobeier
2020-05-13 22:09:01 +08:00
yo,我很喜欢用这个题目考前端面试者。
jhdxr
2020-05-13 22:21:18 +08:00
@jmc891205 ???你是认真的? ruby 才是万物皆 object 吧。。。

补充:
关于这一点我去搜了下,我的确搜到
> Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attribute called path. And so forth.
> Still, this begs the question. What is an object? Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4).

我觉得一个没有属性,也没有方法,也不能被子类化的东西,把它定义为 object 有点牵强?
chizuo
2020-05-13 23:12:35 +08:00
其实 python 关于数值,并不存在引用一说,值相同时,指向同一个地址。值不同时,自然地址就变了。
```
>>> x = 1
>>> y = 1
>>> id(x) == id(y)
True
>>> x = 2
>>> id(x) == id(y)
False
>>>
```
julyedu
2020-05-14 11:15:49 +08:00
兄弟们有需要 Python 课程的吗,我可以免费送大家一些
julyedu
2020-05-14 11:16:38 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/671257

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX