I am attempting to write a class whose string representation changes in response to external stimuli. While that effect is obviously possible via other means, I attempted this method first and was surprised when it didn't work, so I now want to know why :)
Given the following class definition: 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 ...I would expect the following behavior: In [130]: testObject = MyClass() In [131]: testObject.setEdit() In [132]: str(testObject) Out[132]: 'I, <__main__.MyClass object at 0x511270>, am being edited' Unfortunately, this is what happens instead: In [130]: testObject = MyClass() In [131]: testObject.setEdit() In [132]: str(testObject) Out[132]: '<__main__.MyClass object at 0x511270>' In other words, str() is _NOT_ apparently calling <object>.__str__ as it's supposed to! However, calling __str__ directly (which, yes, you're not supposed to do) does work as expected: In [133]: testObject.__str__() Out[133]: 'I, <__main__.MyClass object at 0x511270>, am being edited' Now, my understanding is that functions/methods are first-order objects, and can be pointed to via reference, and that appears to be true: In [135]: def func1(): .....: print "I'm func1" .....: In [136]: def func2(): .....: print "I'm func2" .....: In [137]: func2 = func1 In [138]: func2() I'm func1 However, expressions such as self.__str__ = <some function or method> aren't working for me, as above. Why not? Thanks for any responses, Jeff -- Jeffrey E. Forcier Junior Developer, Research and Development Stroz Friedberg, LLC 15 Maiden Lane, 12th Floor New York, NY 10038 [main]212-981-6540 [direct]212-981-6546 http://www.strozllc.com This message is for the named person's use only. It may contain confidential, proprietary or legally privileged information. No right to confidential or privileged treatment of this message is waived or lost by any error in transmission. If you have received this message in error, please immediately notify the sender by e-mail or by telephone at 212.981.6540, delete the message and all copies from your system and destroy any hard copies. You must not, directly or indirectly, use, disclose, distribute, print or copy any part of this message if you are not the intended recipient. -- http://mail.python.org/mailman/listinfo/python-list