可彬()在Python 2.6被重载就像十月()和十六进制()? [英] Can bin() be overloaded like oct() and hex() in Python 2.6?

查看:124
本文介绍了可彬()在Python 2.6被重载就像十月()和十六进制()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.6(或更早)的十六进制()十月()内置功能可以通过定义一个类重载 __ __(十六进制) __ __月特殊功能。但是没有一个 __斌__ 重载的Python 2.6的新的的行为特殊功能斌()内置功能。

In Python 2.6 (and earlier) the hex() and oct() built-in functions can be overloaded in a class by defining __hex__ and __oct__ special functions. However there is not a __bin__ special function for overloading the behaviour of Python 2.6's new bin() built-in function.

我想知道是否有灵活地超载斌(),如果没有我想知道为什么不一致的接口?

I want to know if there is any way of flexibly overloading bin(), and if not I was wondering why the inconsistent interface?

我不知道 __ __指数可用于特殊的功能,但这并不灵活,因为它只能返回一个整数。我的具体使用情况是从位串模块,其中前导零位被认为是显著:

I do know that the __index__ special function can be used, but this isn't flexible as it can only return an integer. My particular use case is from the bitstring module, where leading zero bits are considered significant:

>>> a = BitString(length=12)       # Twelve zero bits
>>> hex(a)
'0x000'
>>> oct(a)
'0o0000'
>>> bin(a)
'0b0' <------ I want it to output '0b000000000000'

我怀疑有没有实现这一目标的方式,但我认为它不会伤害问!

I suspect that there's no way of achieving this, but I thought it wouldn't hurt to ask!

推荐答案

我觉得简单的答案是:不,斌()不能超载像十月()十六进制()

I think the short answer is 'No, bin() can't be overloaded like oct() and hex().'

至于为什么,答案必须位于与Python 3.0,它使用 __指数__ 超载十六进制()十月()斌(),并已删除了 __月__ __ __(十六进制)特殊功能完全。

As to why, the answer must lie with Python 3.0, which uses __index__ to overload hex(), oct() and bin(), and has removed the __oct__ and __hex__ special functions altogether.

所以,Python的2.6 斌()看起来非常像这真是一个Python 3.0的功能,一直没有,它的处事新的Python 3太多的考虑后移植方式,而不是旧的Python 2路。我还猜想,它不可能得到固定,即使它被认为是一个错误。

So the Python 2.6 bin() looks very much like it's really a Python 3.0 feature that has been back-ported without much consideration that it's doing things the new Python 3 way rather than the old Python 2 way. I'd also guess that it's unlikely to get fixed, even if it is considered to be a bug.

这篇关于可彬()在Python 2.6被重载就像十月()和十六进制()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆