Heim  >  Artikel  >  Backend-Entwicklung  >  python的id()函数解密过程

python的id()函数解密过程

WBOY
WBOYOriginal
2016-06-16 08:46:571072Durchsuche

>>> a = 2.5
>>> b = 2.5
>>> c = b
>>> a is c
False

>>> a = 2
>>> b = 2
>>> c = b
>>> a is c
True

今天在使用is函数的时候去打印a,b分别被赋值为2.5 和2的情况,发现:
>>> a = 2
>>> b = 2
>>> id(a)
21132060
>>> id(b)
21132060
>>> a = 2.5
>>> b = 2.5
>>> id(a)
19622112
>>> id(b)
29321464

当a,b为2的时候id相同,而为2.5的时候不同,这种情况在string字符串的时候也会出现,即当很短的a,b赋值很短的字符串的时候,它们的id值相同,而很长的则不会;
之后,可以得到一个简单的结论就是:解释器在对值很小的int和很短的字符串的时候做了一点小优化,只分配了一个对象,让它们id一样了。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn