开发者

Why doesn't id()'s result on IronPython equal to id()'s result on Python?

开发者 https://www.devze.com 2023-04-12 21:58 出处:网络
I really confuse that a behavior of id() function on IronPython who differ from Python. Let me show you the following code,

I really confuse that a behavior of id() function on IronPython who differ from Python. Let me show you the following code,

In IronPython:

>> s = "hello"
>> a = len(s)
>> id(a)
44
>> a = len(s)
>> id(a)
45

As you can see that, id()'s result is changed in every calls. In Python, however, not be changed.

In Python:

>> s = "hello"
>> a = len(s)
>> id(a)
2633845
>> a = len(s)
>> id(a)
2633845

I know id() function returns an object identification number(ID) of its single parameter. Why does tw开发者_开发问答o python interpreters give me a different result?


CPython has a cache of constant small integers that are used whenever needed. This pool of integers is an optimisation and improves the performance because a new object does not need to be allocated for every small integer as needed. Evidently IronPython handles this differently.

That said, the id() function returns a number which uniquely identifies an object. You can use this to see whether two names are bound to the same object. You cannot use this value to see whether two objects are "equal" in any sense.


http://docs.python.org/library/functions.html#id

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

Python implementation detail: This is the address of the object in memory.

Why do you think ids would be constant?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号