FAQ: __str__ vs __repr__
Andreas Kostyrka
andreas at kostyrka.org
Wed Jun 15 09:12:37 EDT 2005
Well, It means that eval(repr(x)) == x if at all possible.
Basically:
repr('abc') -> 'abc'
str('abc') -> abc
You'll notice that 'abc' is a valid python expression for the string,
while abc is not a valid string expression.
Andreas
On Wed, Jun 15, 2005 at 02:46:04PM +0200, Jan Danielsson wrote:
> Sorry, but I Just Don't Get It. I did search the 'net, I did read the
> FAQ, but I'm too dumb to understand.
>
> As far as I can gather, __str__ is just a representation of the
> object. For instance:
>
> class ServerConnection:
> def __str__(self):
> buf = "Server: " + self.name + "\n"
> buf += "Sent bytes: " + str(self.sentBytes) + "\n"
> buf += "Recv bytes: " + str(self.recvBytes) + "\n"
> return buf
>
> However, I don't understand what __repr__ should be. There's a phrase
> in the documentation which makes it highly confusing for a beginner like
> me: "If at all possible, this should look like a valid Python expression
> that could be used to recreate an object with the same value (given an
> appropriate environment).". What does that mean? Does it mean that I
> should return:
>
> def __str__(self):
> buf = "self.name=" + self.name + "\n"
> buf += "self.sentBytes=" + str(self.sentBytes) + "\n"
> buf += "self.recvBytes=" + str(self.recvBytes) + "\n"
> return buf
>
> ..or is there some other "valid Python expression" format which I
> have yet to encounter?
> --
> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list