About id behavior in an instance method

I have the following script:

class A(object):
    def f(self):

a = A()
b = A()
print map(id, [A.f, a.f, b.f])
print map(id, [a.f, b.f]) 



[4299312976, 4298026672, 4299370816]
[4299312976, 4298026672]


  • Why id

    of A.f

    becomes id

    of A.f

  • why id

    of A.f

    becomes id

    out b.f


Now I am doing this:

print "{0} {1} {2}".format(id(A.f), id(a.f), id(b.f))



4299312976 4299312976 4299312976


Why do they have the same ones now id



source to share

1 answer

When accessed, A.f

an object of type is created <unbound method>

. You can see that it is like this:

print map(id, [A.f, A.f, A.f])


where the value id

will not be the same. The same happens for A.f

and b.f

, but in this case the type <bound method>

, because the object remembers which instance the code should act on.

These objects are garbage collected when you no longer reference them. So:

map(id, [A.f, a.f, b.f])


creates 3 objects (4 including the list containing them) and passes them to the function id

. Once the call is map

complete and the objects are collected and the memory is freed.

In the second call, new objects are created and the memory for the object created for has A.f

been reused (so you get the same id


In the last example, you call id

explicitly each time on an object that is immediately discarded and the memory is immediately reused.

This appears to be the "magic" creation of an object when accessing a method is due to handles .



All Articles