如何为类添加十六进制函数支持

3

我编写了一个类,它实现了__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接受?

1个回答

5
根据hex(..)文档的规定,您需要定义__index__方法:

hex(x)

(..)

如果x不是Python int对象,则必须定义一个返回整数__index__()方法。

(部分省略,已格式化)

因此,对于您的情况,可能是这样的:

class MyClass:
    def __init__(self, value):
        self._value = value

    def __int__(self):
        return self._value

    def __index__(self):
        return self.__int__() #note you do not have to return the same as __int__

当在控制台中运行以下命令时:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class MyClass:
...     def __init__(self, value):
...         self._value = value
...     
...     def __int__(self):
...         return self._value
...     
...     def __index__(self):
...         return self.__int__()
... 
>>> foo=MyClass(14)
>>> hex(foo)
'0xe'

如果您希望hex(..)的“值”是其他内容,您可以定义与__int__不同的__index__,尽管我强烈建议不要这样做。此外,hex(..)保证将返回格式正确的十六进制数字字符串(str):例如,您不能返回元组等。否则它会引发TypeError。例如:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __index__ returned non-int (type tuple)

如果__index__返回一个元组。

在Python2中,实现__hex__确实是可能的。 - Demi-Lune

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接