开发者

Python proper use of __str__ and __repr__

开发者 https://www.devze.com 2022-12-29 18:47 出处:网络
Mycurrent开发者_如何学编程 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

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


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.


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).


__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.

0

精彩评论

暂无评论...
验证码 换一张
取 消