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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to