I want to extend the __str__() method of my object. The str(obj) currently reads:
<mymodule.Test object at 0x2b1f5098f2d0>
I like the address as a unique identifier, but I want to add some attributes. What's the best way to extend this while still keeping the address portion? I'd like to look something like this:
<mymodule.Test object at 0x2b1f5098f2d: name=foo, isValid=true>
I dont' see any attribute that stores the address. I'm using python 2.4.3.
Edit: Would be nice to know how to do this with __repr__()
Solution (for python 2.4.3):
def __repr__(self):
return "<%s.%s object at %s, name=%s, isValid=%s>" % (self.__module__,
self.__class__.__name__, hex(id(self)), self.name, self.isValid)
You can get the address with
id(obj). You probably want to change the__repr__()method instead of__str__(). Here's code that will do this in Python 2.6+:Test with:
You could easily do the same sort of thing in an older version of Python by using string formatting operations like
"%s"instead of the clearerstr.format()syntax. If you are going to usestr.format(), you can also use its built-in hex formatting capability by using{1:#x}in the template and changing argument 1 fromhex(id(self))to simplyid(self).