Is " a is b " and " id(a) == id(b) " the same?

Erik Max Francis max at alcyone.com
Sun Mar 16 07:24:33 CET 2003


Chen wrote:

> Some one said that " a is b " is the same as " id(a) == id(b) ". But
> it
> seems not always true from the following codes:
> 
> >>> class a:
> ...     def f(self):
> ...         pass
> ...     g=f
> 
> >>> b=a()
> >>> print id(a.f), id(b.f), id(a.g), id(b.g)
> 6759528 6759528 6759528 6759528
> >>> print a.f is b.f
> False
> >>> print a.f is a.g
> False
	...

a is b is the same as id(a) == id(b), provided that a and b are of the
same "thing."  There are rare cases in which objects with the same ID
(which in CPython just represents an address) are actually distinct
objects.  In your case, a is a class, but c is an _instance_ of a class.
So a.f is an unbound method, but b.f is a bound method.  They're the
same method, but they're different forms.  The easiest way to see this
is to get the repr of the objects themselves:

>>> class a:
...  def f(self): pass
... 
>>> b = a()
>>> a
<class __main__.a at 0x8117644>
>>> b
<__main__.a instance at 0x8159664>
>>> a.f
<unbound method a.f>
>>> b.f
<bound method a.f of <__main__.a instance at 0x8159664>>

As far as I know, this is a CPython implementation detail; in Jython,
unbound and bound methods have different IDs.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ But since when can wounded eyes see / If we weren't who we were
\__/ Joi
    Blackgirl International / http://www.blackgirl.org/
 The Internet resource for black women.




More information about the Python-list mailing list