substitution __str__ method of an instance
Duncan Booth
duncan.booth at invalid.invalid
Fri Oct 24 06:04:32 EDT 2008
Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
> 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.
>
Another option would be to just change the class of the object:
>>> class C(object):
pass
>>> c = C()
>>> print c
<__main__.C object at 0x01180C70>
>>> def wrapstr(instance, fn=None):
if fn is None:
def fn(self): return "I'm an object"
Wrapper = type(instance.__class__.__name__, (instance.__class__,),
{'__str__':fn})
instance.__class__ = Wrapper
>>> wrapstr(c)
>>> print c
I'm an object
>>> isinstance(c, C)
True
>>> type(c)
<class '__main__.C'>
>>> wrapstr(c, lambda s: "object %s at %s" % (type(s).__name__, id(s)))
>>> print c
object C at 18353264
(I'll leave enhancing wrapstr so that it avoids multiple levels of
wrapping as an exercise for anyone who actually wants to use it.)
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list