getattr(foo, 'foobar') not the same as foo.foobar?

Dave Kuhlman dkuhlman at rexx.com
Thu Mar 13 18:06:05 EDT 2008


The following code has me mystified:

In [4]: class A(object):
   ...:     def show(self):
   ...:         print 'hello'
   ...:
   ...:
In [5]: a = A()
In [6]:
In [7]: x = a.show
In [8]: y = getattr(a, 'show')
In [9]: x
Out[9]: <bound method A.show of <__main__.A object at 0xb557d0>>
In [10]: y
Out[10]: <bound method A.show of <__main__.A object at 0xb557d0>>
In [11]:
In [12]: id(x)
Out[12]: 12419552
In [13]: id(y)
Out[13]: 12419872
In [14]:
In [15]: x is y
Out[15]: False
In [16]:
In [17]: x()
hello
In [18]: y()
hello

Basically, the above code is saying that foo.foobar is not the same as
getattr(foo, 'foobar').

But the documentation at
http://docs.python.org/lib/built-in-funcs.html#l2h-33
says that they are equivalent.

And, the following seems even worse:

  >>> id(getattr(a, 'show')) == id(a.show)
  True
  >>> getattr(a, 'show') is a.show
  False

What gives?  This breaks my understanding of id(), the is operator, and
getattr().

Can someone help me make sense of this?

I'm using Python 2.5.2.

- Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman




More information about the Python-list mailing list