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

Diez B. Roggisch deets at nospam.web.de
Thu Mar 13 19:44:28 EDT 2008


> My understanding is that foo.bar does *not* create a new object.

Your understanding is not correct.

>  All it
> does is return the value of the bar attribute of object foo.  What new
> object is being created?

A bound method. This happens through the descriptor-protocol. Please see 
this example:


class Foo(object):
     def bar(self):
         pass


f = Foo()
a = Foo.bar
b = f.bar
c = f.bar

print a, b, c
print id(b), id(c)


The result is this:


<unbound method Foo.bar> <bound method Foo.bar of <__main__.Foo object 
at 0xbf650>> <bound method Foo.bar of <__main__.Foo object at 0xbf650>>
315560 788960

So b and c really are different objects - "a is not b == True"

Diez



More information about the Python-list mailing list