substitution __str__ method of an instance

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Oct 23 08:40:17 EDT 2008


netimen a écrit :
> 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?

Now that others told you you couldn't do so, there's eventually a 
workaround - that is, if you have the hand on class Foo:

class Foo(object):
     def __str__(self):
         printer = getattr(self, 'printer', super(Foo, self).__str__)
         return printer()

HTH



More information about the Python-list mailing list