Trying to change the __unicode__ method to an instance after creating it creates different results in Python 2.5 and 2.6.
Here's the test script:
class Dummy(object): def __unicode__(self): return u'one' def two(self): return u'two' d = Dummy() print unicode(d) d.__unicode__ = d.two print unicode(d) print d.__unicode__()
In Python 2.5, this creates
one two two
That is, modifying the __unicode__ instance also modifies unicode(instance)
In Python 2.6, this produces
one one two
So, after changing unicode(instance) and instance.__unicode__() , different results are returned.
Why? How can I get this to work on Python 2.6?
(For what it's worth, the use case here is that I want to add something to the __unicode__ output for all subclasses of a given class, without changing the code of the subclasses.)
Edit to make use case a little understandable
I have a class A that has many subclasses. These subclasses define simple __unicode__ methods. I want to add logic so that for instances of a subclass of class A, the unicode (instance) gets something that was attached to the end. To keep the code simple, and because there are many subclasses that I donβt want to change, I would prefer to avoid editing the subclass code.
This is actually existing code that works in Python 2.5. This is something like this:
class A(object): def __init__(self): self._original_unicode = self.__unicode__ self.__unicode__ = self.augmented_unicode def augmented_unicode(self): return self._original_unicode() + u' EXTRA'
This is code that no longer works on 2.6. Any suggestions on how to achieve this without changing the subclass code? (If the answer involves metaclasses, note that class A itself is a subclass of another class - django.db.models.Model. - with a rather complex metaclass)