Can you use self in __str__

Shiyao Ma i at
Sat Nov 29 04:55:55 CET 2014

2014-11-29 11:36 GMT+08:00 Chris Angelico <rosuav at>:
> You can use id() on any object. You are guaranteed to get back an
> integer which is both stable and unique among all ids of objects that
> exist at the same time as the one you called it on. For as long as the
> object continues to exist, that number *will* stay the same. Sometimes
> that's all you need; for instance, imagine a simple mail server which
> produces logs like this:
> [142857] Beginning processing of message
> [142857] Parsing headers
> [314159] Beginning processing of message
> [314159] Parsing headers
> [142857] Storing in destination mailbox
> [314159] Connecting to destination server
> [142857] Finished processing of message
> [314159] Message accepted by destination
> [271871] Beginning processing of message
> [314159] Finished processing of message
> You can easily see, from the initial numbers, what log lines are
> associated with what messages. (Note that emails have their own IDs,
> which could in theory be used, but the id() of an internal dict can be
> used even before the email's ID has been read - as you see from the
> example, a log entry for "Parsing headers" has to be made prior to
> info from the headers being used.) It's not a problem if another
> 142857 comes up later on; there's a very clear begin and end to the
> message, and you're guaranteed that nothing can possibly be
> interspersed with a colliding ID.
> In other implementations of Python, these numbers might look less
> arbitrary (Jython, I believe, allocates them sequentially); but the
> code will work just as well on any compliant implementation of the
> language, because everything I've said above is a language guarantee,
> not a CPython implementation detail.
> ChrisA

Thanks. Informed.
The implementation dependent thing is "id(obj)" == virtual mem addr
(which caused my bad feeling).
Apparently have nothing to do with it here, though.

And 'id' is seemingly great to differentiate each obj.



More information about the Python-list mailing list