Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

python - Same value for id(float)

As far as I know, everything is object in Python and the id() should (am I right?) return a different number for each object.

In my case, id(1) returns 4298178968, id(2) returns 4298178944 but I get the same values for all float types, id(1.1) returns 4298189032, id(2.2) also returns 4298189032 and more.

Why I get the same id for all float values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Python can reuse memory positions.

When you run:

id(1.1)

you create a float value, ask for its id(), and then Python deletes the value again because nothing refers to it. When you then create another float value, Python can reuse the same memory position and thus id(2.2) is likely to return the same value for id():

>>> id(1.1)
140550721129024
>>> id(2.2)
140550721129024

Do this instead:

float_one, float_two = 1.1, 2.2
print id(float_one), id(float_two)

Now the float values have references to them (the two variables) and won't be destroyed, and they now have different memory positions and thus id() values.

The reason you see different id() values for small integers (from -5 through to 256) is because these values are interned; Python only creates one 1 integer object and re-uses it over and over again. As a result, these integers all have a unique memory address regardles, as the Python interpreter itself already refers to them, and won't delete them until the interpreter exits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...