substitution __str__ method of an instance

netimen netimen at gmail.com
Thu Oct 23 04:49:52 EDT 2008


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?



More information about the Python-list mailing list