解析:
赋值(=),就是创建了对象的一个新的引用,修改其中任意一个变量都会影响到另一个。
浅拷贝:创建一个新的对象,但它包含的是对原始对象中包含项的引用(如果用引用的方式修改其中一个对象,另外一个也会修改改变){1,完全切片方法; 2,工厂函数,如 list(); 3,copy 模块的 copy()函数}
深拷贝:创建一个新的对象,并且递归的复制它所包含的对象(修改其中一个,另外一个不会改变){copy 模块的 deep.deepcopy()函数}
顺便问下大家,现在 V2EX 的兄弟们还有需要 python 课程的吗,我可以免费送大家一些优质课程,绝对免费!
1
jmc891205 2020-05-13 18:02:04 +08:00
a = 1
b = a 这算赋值、浅拷贝还是深拷贝 |
3
Vegetable 2020-05-13 18:34:08 +08:00
你们两个给我整楞了,一楼大哥是考教还是真问啊。
python 里数字本身是不可变对象,并不存在 shallow copy 和 deep copy 的区别,一旦区分深浅,那必然是复合对象。 |
4
kkk330 2020-05-13 18:59:30 +08:00 via iPhone
别忘了小整数池
|
5
jhdxr 2020-05-13 19:34:12 +08:00
@lxd152 先不说一楼这个例子是数字。。。就你单纯这描述『 b 指向 a 的内存』这明显也是赋值(按照正文中的三种分类方式)啊。。。
|
7
lxd152 2020-05-13 20:04:46 +08:00
|
8
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] ``` |
11
qiaobeier 2020-05-13 22:09:01 +08:00
yo,我很喜欢用这个题目考前端面试者。
|
12
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 有点牵强? |
13
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 >>> ``` |
14
julyedu OP 兄弟们有需要 Python 课程的吗,我可以免费送大家一些
|