kyo guan wrote: > Can someone explain why the id() return the same value, and why > these values are changing? Thanks you.
>>>> a=A() >>>> id(a.f) > 11365872 >>>> id(a.g) > 11365872 >>>> 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. >>> A.f <unbound method A.f> >>> A().f <bound method A.f of <__main__.A instance at 0x64198>> >>> 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. >>>> a.f is a.g > False 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. >>>> id(a.f), id(a.g), id(b.f), id(b.g) > (11492408, 11492408, 11492408, 11492408) >>>> a.f is a.g > False >>>> id(a.f), id(a.g), id(b.f), id(b.g) > (11365872, 11365872, 11365872, 11365872) >>>> 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 [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list