Extending __str__() rather than replacing it
-
15-02-2021 - |
Question
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)
La solution
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+:
class Test(object):
def __repr__(self):
repr_template = ("<{0.__class__.__module__}.{0.__class__.__name__}"
" object at {1}: name={0.name}, isValid={0.isValid}>")
return repr_template.format(self, hex(id(self)))
Test with:
test = Test()
test.name = "foo"
test.isValid = True
print repr(test)
print str(test)
print test
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 clearer str.format()
syntax. If you are going to use str.format()
, you can also use its built-in hex formatting capability by using {1:#x}
in the template and changing argument 1 from hex(id(self))
to simply id(self)
.
Autres conseils
class Mine(object):
def __str__(self):
return object.__str__(self) + " own attributes..."