Understanding descriptors

Aahz aahz at pythoncraft.com
Wed Feb 4 23:01:02 CET 2009

In article <mailman.8322.1233272628.3487.python-list at python.org>,
Brian Allen Vanderburg II  <BrianVanderburg2 at aim.com> wrote:
>  [...]
>When a lookup is done it uses this descriptor to make a bound or unbound 
>C.F # unbound method object, expects explicit instance when calling the 
>c.F # bound method object provides instance implicitly when calling the 
>This is also done when adding to the classes:
>C.f1 = f1
>f1 # function
>C.f1 # unbound method
>c.f1 # bound method
>To prevent this it has to be decorated so the descriptor doesn't cause 
>the binding:
>C.f2 = staticmethod(f1)
>C.f2 # functon
>c.f2 # function
>Here is a question, why don't instance attributes do the same thing?
>c.f3 = f1
>c.f3 # function, not bound method
>So it is not calling the __get__ method for c.f3  After it finds c.f3 in 
>c.__dict__, and since it has a getter, shouldn't it call the __get__ to 
>return the bound method.  It is good that it doesn't I know, but I just 
>want to know why it doesn't from an implementation view.

This is a bit beyond my expertise, but nobody else has responded, so I'll
take a stab at it:

Basically, this is part of the design philosphy that keeps everything
working the same way.  When an attribute is found on an instance, it
gets returned unmodified.  Period.  In other words, the fact that f3
happens to return a function object gets ignored.  You can force f3 to
work like a bound method by defining it as one:

def f3(self):

If you use a new-style class or Python 3.0, the same design is evident
when you try to use e.g. str() to call the __str__() special method: the
instance gets ignored for looking up the method.
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.

More information about the Python-list mailing list