How does "delegation" work as per the FAQ?

Mike C. Fletcher mcfletch at rogers.com
Thu Dec 25 22:29:56 CET 2003


Rene Pijlman wrote:

>Ville Vainio:
>  
>
>>Rene Pijlman:
>>    
>>
>>>__getattr__: "Called when an attribute lookup has not found the attribute
>>>in the usual places". There is no mention of method calls.
>>>      
>>>
>>A method is an attribute.
>>    
>>
>
>I see. But how are the arguments of a method call passed on, when
>delegation is implemented this way?
>  
>
Jeff already gave you a fairly brief description of why this is so, but 
I'll try to flesh it out somewhat.  In Python, methods of objects are 
actually themselves objects which wrap up an implementation function 
(also an object) and a reference to the object on which they are to act 
(the "self" parameter).  To demonstrate this:

 >>> class x(object):
...     def y( self, value ):
...         print value
...        
 >>> item = x()
 >>> item
<__main__.x object at 0x011EA4B0>
 >>> item.y
<bound method x.y of <__main__.x object at 0x011EA4B0>>
 >>> x.y
<unbound method x.y>
 >>> item.y.im_self
<__main__.x object at 0x011EA4B0>
 >>> item.y.im_func
<function y at 0x011E4108>
 >>> item.y.__call__
<method-wrapper object at 0x00ED3B78>

So, when you do item.y( somevalue ), you are doing this set of actions:

    * doing an attribute lookup in the object item for the attribute name y
          o in this example, this finds the unbound method x.y in the
            class, which (via various hooks (see discussions of
            "descriptors")) generates a new bound method object (item.y)
            for the instance "item" and returns that.
          o in the sample code you found, the methods for the file
            object would not be found in the instance "item"'s
            dictionary or class' dictionary, so the __getattr__ hook
            (which is called when an attribute lookup fails) would be
            called and accomplish the delegation by doing another
            attribute lookup from the object to which it is delegating
            responsibility.
    * calling the __call__ method of the (newly created) bound method
      object with the arguments (somevalue)
          o in this example, the bound method has a reference to "item"
            which it will pass as the first argument to it's underlying
            "y" function, so the arguments passed to the function are
            (item, somevalue) (corresponding to self, somevalue in the
            method signature).
          o In the sample code, the bound method would have a reference
            to the delegated file, rather than the delegating object, so
            it will act on the underlying file.

Enjoy yourself,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/








More information about the Python-list mailing list