substitution __str__ method of an instance

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 23 23:49:33 CEST 2008


On Thu, 23 Oct 2008 10:55:56 +0200, Christian Heimes wrote:

> netimen wrote:
>> How can I substitute __str__ method of an instance?
> 
> It's not possible. For performance and other reasons most __*__ methods
> are looked up on the type only.
> 
> Christian

However, you can dispatch back to the instance if you really must:


class MyObj(object):
    def __init__(self):
        self.__str__ = lambda self: "I'm an object!"
    def __str__(self):
        return self.__str__(self)


But honestly, this sounds like a bad idea. If instances of the one class 
have such radically different methods that they need to be treated like 
this, I question whether they actually belong in the same class.




-- 
Steven



More information about the Python-list mailing list