Python:两个对象相同 [英] Python: two objects are the same

查看:93
本文介绍了Python:两个对象相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
对象和基本类型的分配

Possible Duplicate:
Assignment of objects and fundamental types

a = [1,2,3]
b = a
print b is a

此代码显示True.为什么?如果两个变量指向相同的对象,则"is"仅返回True,在这种情况下,它们是具有相同值的不同对象. "=="将返回True,但"is"则不会.

This code prints True. Why? "is" only returns True if the two variables point to the same object, when in this case they're different objects with the same value. "==" would return True, but "is" shouldn't.

但是,自

b.reverse()
print a,b

打印[3,2,1] [3,2,1],就解释器而言,它们似乎是同一对象,对b的操作将自动在a上执行.同样,为什么呢?我以前从未见过这样的事情.

prints [3, 2, 1] [3, 2, 1], it seems that as far as the interpreter is concerned, they ARE the same object, and operations on b will automatically be performed on a. Again, why? I've never seen anything like this happen before.

推荐答案

执行a = [1, 2, 3]时,会将名称a绑定到列表对象.当您执行b = a时,会将名称b绑定到任何a-在这种情况下为列表对象.因此,它们是相同的...一个对象可以有多个名称.值得阅读 Python数据模型.

When you do a = [1, 2, 3] you're binding the name a to a list object. When you do b = a, you're binding the name b to whatever a is - in this case the list object. Ergo, they're the same... An object can have multiple names. It's worth reading up on the Python Data Model.

如果要复制listobj,则可以查看b = a[:]以使用slice创建浅表副本,或使用copy.copy进行浅表副本(应适用于任意对象),或奇怪的是-深拷贝.

If you wanted to make a copy of your listobj, then you can look at b = a[:] to use slice to create a shallow copy, or copy.copy for a shallow copy (should work on arbitary objects), or copy.deepcopy for strangely - a deep copy.

您还将在CPython中发现一些令人惊讶的东西,它可以缓存短字符串/小整数...

You'll also notice something surprising in CPython which caches short strings/small integers...

>>> a = 4534534
>>> b = a
>>> a is b
True
>>> b = 4534534
>>> a is b
False
>>> a = 1
>>> b = a
>>> a is b
True
>>> b = 1
>>> a is b
True

这篇关于Python:两个对象相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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