我编写了一个类,它实现了__int__
方法,以便实例可以像整数一样运行:
class MyClass:
def __init__(self, value):
self._value = value
def __int__(self):
return self._value
在实例上使用 int
函数是有效的,我认为其他内置函数也会隐式地依赖它,例如 hex
。然而,我得到了以下错误信息:
>>> x = MyClass(5)
>>> int(x)
5
>>> hex(x)
TypeError: 'MyClass' object cannot be interpreted as an integer
我曾尝试以与__int__
相同的方式实现__hex__
方法,但这没有产生任何效果。
我该怎么做才能让我的类的实例被hex
接受?
__hex__
确实是可能的。 - Demi-Lune