问题
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
回答1:
The __repr__
should preferably be a string that could be used to recreate the object, for example if you use eval
on it - see the docs here. This isn't an exact science, as it can depend on how the user of your module imported it, for example.
I would have the __str__
return the binary string, and the __repr__
return Classname(binary_string)
, or whatever could be used to recreate the object.
In the bitstring module (which I maintain) the __str__
is hexadecimal if the bitstring is a multiple of 4 bits long, otherwise it's either binary or a combination of the two. Also if the bitstring is very long then it gets truncated (you don't want to try to print a 100 MB bitstring in an interactive session!)
I'd avoid using the bin()
function altogether if I were you. The reason being that it can't be used if your bitstring starts with zero bits (see my question here). I'd advise using either use a bin
method or property instead.
回答2:
I'd consider having __str__
return a hexadecimal representation instead. This way, it's easier to eyeball what the actual bit values are, and thus more useful. But still quite concise (in fact, fewer characters than the decimal representation).
回答3:
__repr__
needs to return something that, if passed to your constructor, would create a new object that is an identical copy of the original one.
Yours returns '11' but if you passed '11' to your constructor you would not get the same bitfield as a result. So this __repr__
is not ok.
来源:https://stackoverflow.com/questions/2812809/python-proper-use-of-str-and-repr