如何在模拟类中支持%x格式化

2024-09-28 19:10:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我还没找到办法。我使用的是Python 3.6.1(v3.6.1:69c0db50502017年3月21日,01:21:04)。Sierra下的MacOS,不过我们需要这个来处理Python2。你知道吗

我有一个自定义类,它做了一些类似int的子字段解码。因为我自己的原因,我想两样都能做

inst * 4

以及

inst.subfield << 1

(其中子字段是inst的属性)。这些对象是高度重载的,例如打印inst将转储子字段以供查看。你知道吗

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

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

我确实重载了__int__,并且int(inst)按预期返回一个整数。你知道吗

有什么办法能让这件事成功吗?这是个小麻烦,但我想解决一下。你知道吗

此外,我还实现了__format__。所以'{0:x}'.format(inst)行得通,但上面的打印却不行

谢谢!你知道吗


Tags: 对象format高度属性原因macos整数解码
1条回答
网友
1楼 · 发布于 2024-09-28 19:10:22

您需要实现^{}^{}

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

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

输出:

0x2a

^{}的文档中:

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中的相关源代码可以看出。你知道吗

相关问题 更多 >