This is an old copy of the Python FAQ. The information here may be outdated.

What is delegation?

Delegation is an object oriented technique (also called a design pattern) where certain operations on one object are automatically applied to another, usually contained, object.

Let’s say you have an object x and want to change the behaviour of just one of its methods. To solve this, you can create a new class that contains x, provides a new implementation of the method you’re interested in changing, and delegates all other methods to the corresponding method of x.

Delegation is easy in Python. For example, here’s a simple class that behaves like a file but converts all written data to uppercase:

class UpperOut:
      def __init__(self, outfile):
            self._outfile = outfile
      def write(self, s):
            self._outfile.write(s.upper())
      def __getattr__(self, name):
            return getattr(self._outfile, name)

The UpperOut class adds a write() method that converts the argument string to uppercase, before calling the corresponding method on the self._outfile object. All other methods are delegated directly to the self._outfile object, via the __getattr__ method.

See the language reference (dead link) for more information about controlling attribute access.

Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a __setattr__ method too, and it must do so carefully. The basic implementation of __setattr__ is roughly equivalent to the following:

class X:
     ...
     def __setattr__(self, name, value):
          self.__dict__[name] = value
     ...

Note that most __setattr__ implementations must modify the objects __dict__ attribute directly to store local state for self without causing an infinite recursion.

CATEGORY: programming

 

A Django site. rendered by a django application. hosted by webfaction.