gpt4 book ai didi

python - python 中是否存在 __bin__(或 __binary__)运算符?

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:37 25 4
gpt4 key购买 nike

在 Python 中,__oct____hex__运营商的存在是为了为 oct() 实现特定的行为和 hex() .参见 Emulating numeric types

但我不明白为什么__bin__ (或 __binary__ )不存在,而 bin()函数存在于内置函数中。参见 Built-in Functions .

我错过了什么吗?有什么原因吗?

Python 3 的变化

我找到了这个引用 Operators And Special Methods在“Python 3.0 的新增功能”中:

The oct() and hex() special methods are removed – oct() and hex() use index() now to convert the argument to an integer.

最佳答案

您可以使用 object.__index__处理 Python 2 中的 bin() 调用。从 Python 3 开始,它也适用于 hex()oct() 但不适用于Python 2。

来自 Python 3 docs :

object.__index__(self)

Called to implement operator.index(), and whenever Python needs to losslessly convert the numeric object to an integer object (such as in slicing, or in the built-in bin(), hex() and oct() functions). Presence of this method indicates that the numeric object is an integer type. Must return an integer.

它在 Python 2 中没有(清楚地)记录,但也在那里工作:

>>> class A(object):
... def __index__(self):
... return 100
...
>>> bin(A())
'0b1100100'

bin() 的 CPython 代码内部调用 PyNumber_ToBase依次调用 PyNumber_Index并且此函数调用该对象上的 nb_index 插槽。

关于python - python 中是否存在 __bin__(或 __binary__)运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39767750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com