Re: "Aliasing" an object's __str__ to a different method
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

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

From: Christopher Subich <spam.csubich+block@block.subich.spam.com>
Date: Sat Jul 23 2005 - 05:14:42 CEST

ncf wrote:
> Well, suffice to say, having the class not inherit from object solved
> my problem, as I suspect it may solve yours. ;)

Actually, I did a bit of experimenting. If the __str__ reassignment
worked as intended, it would just cause an infinite recursion.

To paste the class definition again:
> class MyClass(object):
>
> def Edit(self):
> return "I, %s, am being edited" % (self)
>
> def View(self):
> return "I, %s, am being viewed" % (self)
>
> def setEdit(self):
> self.__str__ = self.__repr__ = self.Edit
>
> def setView(self):
> self.__str__ = self.__repr__ = self.View

Notice the % (self) in Edit and View -- those recursively call
str(self), which causes infinite recursion.

In the spirit of getting the class working, though, the class-method
behavior of __str__ for new-style classes can be fixed with an extremely
ugly hack:
class MyClass(object):
        def __init__(self):
                self.__str__ = lambda : object.__str__(self)
         def Edit(self):
                 return "I, %s, am being edited"

         def View(self):
                 return "I, %s, am being viewed"

         def setEdit(self):
                 self.__str__ = self.__repr__ = self.Edit

         def setView(self):
                 self.__str__ = self.__repr__ = self.View
         def __str__(self):
                return self.__str__()

(Notice that I've removed the string substitution in Edit and View.
This also does not change the __repr__ method; it also acts as a class
method. But that's also easy enough to change in the same way.)

I also would be interested in knowing why new-style classes treat
__str__ as a class method.
Received on Thu Sep 29 17:07:03 2005