question about the id()

K

kyo guan

HI ALL:

Can someone explain why the id() return the same value, and why these values are changing? Thanks you.

Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information..... def f():
.... pass
.... def g():
.... pass
........ def f():
.... print 1
.... def g():
.... print 3
....
 
A

Andrew Dalke

kyo said:
Can someone explain why the id() return the same value, and why
these values are changing? Thanks you.

The Python functions f and g, inside of a class A, are
unbound methods. When accessed through an instance what's
returned is a bound method.

In your code you do a.f, which creates a new bound method.
After the id() call its ref-count goes to zero and its
memory is freed. Next you do a.g which creates a new
bound method. In this case it reuses the same memory location,
which is why you get the same id.

I know Python keeps free lists for some data types. I
suspect bound method objects are tracked this way because
they are made/destroyed so frequently. That would increase
the likelihood of you seeing the same id value.


This is the first time you have two bound methods at
the same time. Previously a bound method was garbage
collected before the next one was created.

The memory locations changed. Here's a conjecture that
fits the facts and is useful to help understand.

Suppose the free list is maintained as a stack, with
the most recently freed object at the top of the stack,
which is the first to be used for the next object.

The "a.f is a.g" creates two bound methods, one at
11492408 and the other at 11365872. Once the 'is'
is done it dec-refs the two methods, a.f first and
a.g second. In this case the ref counts go to zero
and the memory moved to the free list. At this point
the stack looks like

[11365872, 11492408, ... rest of stack ... ]

You then do a.f. This pulls from the top of the
stack so you get 11365872 again. The id() tells
you that, and then the object gets decrefed and
put back on the stack.


Andrew
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top