"Aliasing" an object's __str__ to a different method

Scott David Daniels Scott.Daniels at Acm.Org
Sat Jul 23 14:18:50 CEST 2005

Jeffrey E. Forcier wrote:
> ...
> However, you appear to be correct, and the docs appear to be confused:
> class MyClass(object):
>         def edit(self):
>                 return "I'm in edit mode"
>         def setEdit(self):
>                 MyClass.__str__ = self.edit
> ...
> Either way, guess I will have to take another route. Your suggestion  is 
> what I'd had in mind, and does the job pretty well. I'm still  
> attempting to figure out the best approach to my overall problem,  
> however, so who knows where I will end up =)

Here is one more standard way to do this:

     class MyClass(object):
         ... # Common behavior goes here

         def setEdit(self):
             self.__class__ = MyEditClass

         def setView(self):
             self.__class__ = MyViewClass

     class MyEditClass(MyClass):
         def __repr__(self):
             return "I, %s, am being edited" % super(
                               MyEditClass, self).__repr__()

     class MyViewClass(MyClass):
         def __repr__(self):
             return "I, %s, am being viewed" % super(
                               MyViewClass, self).__repr__()

Be a little careful about the structure of the subclasses (MyViewClass
and MyEditClass) since they can wink into and out of existence, and
all will go well.  Plus, you can easily override base behavior in the
subclasses differentially.

Note: for this example, you could also define the methods like:

     class MyEditClass(MyClass):
         def __repr__(self):
             return "I, %s, am being edited" % MyClass.__repr__(self)

When to use super rather than direct access to the superclass is an
involved discussion.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list