Python正确使用__str__和__repr__ [英] Python proper use of __str__ and __repr__
问题描述
我当前的项目需要大量使用位字段.我发现了一个简单而实用的位字段类的密码但是它缺少我需要的一些功能,所以我决定扩展它.我只是要实现 __ str __
和 __ repr __
,并且我想确保遵守惯例.
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 __
应该是非正式且简洁的,所以我使它返回了位字段的十进制值(即 str(bit field 11)
将是"3"
.
__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 __
应该是该对象的正式表示形式,所以我已使其返回了实际的位字符串(即 repr(bit field 11)
将是"11"
).
__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"
).
您认为此实现是否符合 str
和 repr
的约定?
In your opinion would this implementation meet the conventions for str
and repr
?
此外,我使用了 bin()
函数来获取存储在该类中的值的位字符串.这与Python<不兼容.2.6,还有其他方法吗?
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?
干杯
Pete
推荐答案
__ repr __
应该最好是可用于重新创建对象的字符串,例如,如果您使用 eval
上-请参见文档此处.这不是一门精确的科学,例如,它取决于模块用户的导入方式.
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.
我将使 __ str __
返回二进制字符串,并且使 __ repr __
返回 Classname(binary_string)
,或者可以用于重新创建的任何东西对象.
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.
在位串模块(我维护)中, __ str __
是如果位串是4位长的倍数,则为十六进制,否则为二进制或两者的组合.另外,如果位串很长,则会被截断(您不想在交互式会话中尝试打印100 MB的位串!)
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!)
如果我是我,我会完全避免使用 bin()
函数.原因是如果您的位串以零位开头,则无法使用它(请参阅我的问题
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.
这篇关于Python正确使用__str__和__repr__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!