Python proper use of __str__ and __repr__

Posted by Peter on Stack Overflow See other posts from Stack Overflow or by Peter
Published on 2010-05-11T17:06:28Z Indexed on 2010/05/11 17:14 UTC
Read the original article Hit count: 241

Hey,

My current project requires extensive use of bit fields. I found a simple, functional recipe for bit a field class but it was lacking a few features I needed, so I decided to extend it. I've just got to implementing __str__ and __repr__ and I want to make sure I'm following convention.

__str__ is supposed to be informal and concice, so I've made it return the bit field's decimal value (i.e. str(bit field 11) would be "3".

__repr__ is supposed to be a official representation of the object, so I've made it return the actual bit string (i.e. repr(bit field 11) would be "11").

In your opinion would this implementation meet the conventions for str and repr?

Additionally, I have used the bin() function to get the bit string of the value stored in the class. This isn't compatible with Python < 2.6, is there an alternative method?

Cheers,

Pete

© Stack Overflow or respective owner

Related posts about python

Related posts about bit-manipulation