我还没找到办法。我使用的是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)
行得通,但上面的打印却不行
谢谢!你知道吗
您需要实现^{} 和^{} :
输出:
从^{} 的文档中:
因此
__index__
由hex()
调用,通过查看PyNumber_ToBase中的相关源代码可以看出。你知道吗相关问题 更多 >
编程相关推荐