substitution __str__ method of an instance

Diez B. Roggisch deets at nospam.web.de
Thu Oct 23 04:55:36 EDT 2008


netimen wrote:

> I couldn't substitute __str__ method of an instance. Though I managed
> to substitute ordinary method of an instance:
> 
> from types import MethodType
> 
> class Foo(object):
>     pass
> 
> class Printer(object):
> 
>     def __call__(self, obj_self):
>         return 'printed'
> 
> f = Foo()
> 
> f.printer = MethodType(Printer(), f, Foo)
> print f.printer()  # works fine - I get: 'printed'
> 
> print f  # get: <__main__.Foo object at 0x00D69C10>
> f.__str__ = MethodType(Printer(), f, Foo)
> print f  # still get: <__main__.Foo object at 0x00D69C10>. Why?
> Foo.__str__ = MethodType(Printer(), None, Foo)
> print f  # works fine - I get: 'printed'
> 
> 
> How can I substitute __str__ method of an instance?

You can't. Special methods are only looked up on classes. 

Diez



More information about the Python-list mailing list