Python中的两个变量具有相同的ID,但没有列表或元组 [英] Two variables in Python have same id, but not lists or tuples

查看:276
本文介绍了Python中的两个变量具有相同的ID,但没有列表或元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中的两个变量具有相同的id:

Two variables in Python have the same id:

a = 10
b = 10
a is b
>>> True

如果我带两个list:

a = [1, 2, 3]
b = [1, 2, 3]
a is b
>>> False

根据

according to this link Senderle answered that immutable object references have the same id and mutable objects like lists have different ids.

因此,根据他的回答,元组应该具有相同的ID-含义:

So now according to his answer, tuples should have the same ids - meaning:

a = (1, 2, 3)
b = (1, 2, 3)
a is b
>>> False

理想情况下,由于元组不是可变的,它应该返回True,但是它返回False

Ideally, as tuples are not mutable, it should return True, but it is returning False!

解释是什么?

推荐答案

不可移植对象没有相同的id,事实上,这对于您单独定义的任何类型的对象都不适用.一般来说,每次在Python中定义对象时,都会创建一个具有新标识的新对象.但是,出于优化的目的(通常),小整数(介于-5和256之间)和内联字符串有一些例外,它们的特殊长度(通常少于20个字符) * 是单例并且具有相同的id(实际上是一个具有多个指针的对象).您可以像下面这样检查:

Immutable objects don't have the same id, and as a mater of fact this is not true for any type of objects that you define separately. Generally speaking, every time you define an object in Python, you'll create a new object with a new identity. However, for the sake of optimization (mostly) there are some exceptions for small integers (between -5 and 256) and interned strings, with a special length --usually less than 20 characters--* which are singletons and have the same id (actually one object with multiple pointers). You can check this like following:

>>> 30 is (20 + 10)
True
>>> 300 is (200 + 100)
False
>>> 'aa' * 2 is 'a' * 4
True
>>> 'aa' * 20 is 'a' * 40
False

对于自定义对象:

>>> class A:
...    pass
... 
>>> A() is A() # Every time you create an instance you'll have a new instance with new identity
False

还请注意,is运算符将检查对象的身份,而不是值.如果要检查值,请使用==:

Also note that the is operator will check the object's identity, not the value. If you want to check the value you should use ==:

>>> 300 == 3*100
True

并且由于没有针对元组或任何可变类型的优化或内部规则,因此,如果您定义任何大小的两个相同元组,它们将获得自己的标识,因此对象也将不同:

And since there is no such optimizational or interning rule for tuples or any mutable type for that matter, if you define two same tuples in any size they'll get their own identities, hence different objects:

>>> a = (1,)
>>> b = (1,)
>>>
>>> a is b
False

值得一提的是,即使在迭代器中定义了单整数"和中间字符串"的规则,它们也是正确的.

It's also worth mentioning that rules of "singleton integers" and "interned strings" are true even when they've been defined within an iterator.

>>> a = (100, 700, 400)
>>>
>>> b = (100, 700, 400)
>>>
>>> a[0] is b[0]
True
>>> a[1] is b[1]
False


*一篇很好且详尽的文章: http://guilload.com/python-string-interning/


* A good and detailed article on this: http://guilload.com/python-string-interning/

这篇关于Python中的两个变量具有相同的ID,但没有列表或元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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