如何在模拟 int 的 class 上支持 %x 格式

How to support %x formatting on a class that emulates int

我还没有找到执行此操作的方法。我在 Python 3.6.1(v3.6.1:69c0db5050,2017 年 3 月 21 日,01:21:04)。 Sierra 下的 MacOS,尽管我们需要它才能在 Python 2.

上工作

我有一个自定义的 class,它做的事情看起来像带有子字段解码的 int。出于我自己的原因,我希望能够像

inst * 4

inst.subfield << 1

(其中 subfield 是 inst 的一个属性)。这些对象高度超载,例如打印 inst 将转储子字段以供查看。

这一切都是通过重载所有自定义函数来处理数学和与其他对象的交互来完成的。总的来说,它工作得很好,但有一个明显的例外:打印。在大多数情况下,用户可能会忘记这不是一个真正的整数并像使用它一样使用它,但是使用整数打印命令将不起作用:

print("%#x"%inst)
TypeError: %x format: an integer is required, not CustomType

我确实 __int__ 超载了,int(inst) returns 是预期的整数。

有什么方法可以让它工作吗?这是一个小问题,但我想解决这个问题。

此外,我确实实施了 __format__。所以 '{0:x}'.format(inst) 有效,但上面的打印无效。

谢谢!

您需要实施 __int__ and __index__:

class X(object):
    def __int__(self):
        return 42
    def __index__(self):
        return 42

x = X()
print('%#x' % x)

输出:

0x2a

来自 __index__ 的文档:

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.

所以__index__是被hex()调用的,查看PyNumber_ToBase中的相关源码可以看出。