سؤال

I am running python 2.7 on Windows7.

In the following, why is the second number in the representation of the weak reference not the same as id(f)?

import weakref

class Foo(object):
    pass

f = Foo()
w = weakref.ref(f)
print("id(f): %s"%(id(f),))
print("w: %s"%(w,))

>>> 36036400
>>> w: <weakref at 022649F0; to 'Foo' at 0225DF30>

Since is says that the weak reference refers to Foo "at 0225DF30" I would have though that this number would be the address of f, which in CPython is supposed to be the same as the id.

هل كانت مفيدة؟

المحلول 2

You seem to expect id(f) to display the same number as if you just print out f. This is not the case, as shown in this example:

>>> f
<__main__.Foo object at 0x10929df10>
>>> id(f)
4448706320
>>> w
<weakref at 0x10928cfc8; to 'Foo' at 0x10929df10>
>>> id(w)
4448636872

The other thing that didn't show up in your example is that in the output of w, the location of 'Foo' is in hexadecimal.

>>> print 0x10929df10
4448706320

Using the numbers from what you gave us:

>>> print 0x0225DF30
36036400

So you can see that the numbers are actually the same; it's just that it's displaying in hex in one place and in decimal in the other.

نصائح أخرى

The integer 36036400 is the same as hexadecimal 0x225df30:

In [10]: hex(36036400)
Out[10]: '0x225df30'

In [11]: 36036400 == 0x225df30
Out[11]: True

You could use %x to see the hexadecimal representation of id(f):

In [12]: print("id(f): %x"%(36036400,))
id(f): 225df30
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top