为什么"[]是[]"?在python中评估为False [英] Why does "[] is [ ]" evaluate to False in python

查看:65
本文介绍了为什么"[]是[]"?在python中评估为False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在交互式python shell中尝试一下.

Try this in an interactive python shell.

[] is [ ]

以上返回False,为什么?

The above returns False, why?

推荐答案

您创建了两个可变对象,然后使用is来查看它们是否是相同的对象 .那肯定应该返回False,否则某些东西将被破坏.

You created two mutable objects, then used is to see if those are the same object. That should definitely return False, or something would be broken.

您永远不会希望is在这里返回true.想象一下,如果您这样做:

You wouldn't ever want is to return true here. Imagine if you did this:

foo = []
bar = []
foo.append(42)

然后,如果bar现在包含42,您会感到非常惊讶.如果is返回true,这意味着两个[]调用都返回了完全相同的对象,则在bar的引用中可以看到附加到foo的内容.

then you'd be very surprised if bar now contains 42. If is returned true, meaning that both [] invocations returned the exact same object, then appending to foo would be visible in the reference to bar.

对于不可变对象,缓存对象是有意义的,此时is 可能返回true,就像使用空元组一样:

For immutable objects, it makes sense to cache objects, at which point is may return true, like with empty tuples:

>>> () is ()  # are these two things the same object?
True

CPython实现优化了空元组的创建;您将始终获得完全相同的对象,因为这样可以节省内存并加快某些操作的速度.因为元组是不可变的,所以这是完全安全的.

The CPython implementation has optimised empty tuple creation; you'll always get the exact same object, because that saves memory and makes certain operations faster. Because tuples are immutable, this is entirely safe.

如果您希望改为测试值相等性,那么您会得到错误的运算符.请使用==运算符:

If you expected to test for value equality instead, then you got the wrong operator. Use the == operator instead:

>>> [] == []  # do these two objects have the same value?
True

这篇关于为什么"[]是[]"?在python中评估为False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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