"Aliasing" an object's __str__ to a different method
Christopher Subich
spam.csubich+block at block.subich.spam.com
Fri Jul 22 23:14:42 EDT 2005
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.
More information about the Python-list
mailing list