faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 1 of 1 people (100%) answered Yes



Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 142, Python FAQ

Packages: faq;oop
4.48. What is delegation?
Delegation refers to an object oriented technique Python programmers may implement with particular ease.
Consider the following: 
from string import upper
class UpperOut:
    def __init__(self, outfile):
          self.__outfile = outfile
    def write(self, str):
          self.__outfile.write( upper(str) )
    def __getattr__(self, name):
          return getattr(self.__outfile, name)
Here the UpperOut class redefines the write method to convert the
argument string to upper case before calling the underlying
self.__outfile.write method, but all other methods are delegated to the
underlying self.__outfile object. The delegation is accomplished via the
"magic" __getattr__ method. Please see the language reference for more
information on the use of this method. 
Note that for more general cases delegation can get trickier. Particularly
when attributes must be set as well as gotten the class must define a
__settattr__ method too, and it must do so carefully. 
The basic implementation of __setattr__ is roughly equivalent to the
   class X:
        def __setattr__(self, name, value):
             self.__dict__[name] = value
Most __setattr__ implementations must modify self.__dict__ to store local
state for self without causing an infinite recursion.