Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在类中添加对十六进制函数的支持_Python_Python 3.x - Fatal编程技术网

Python 如何在类中添加对十六进制函数的支持

Python 如何在类中添加对十六进制函数的支持,python,python-3.x,Python,Python 3.x,我已经编写了一个类,它实现了\uuuuu int\uuuu方法,这样一个实例就可以像一个整数一样工作: class MyClass: def __init__(self, value): self._value = value def __int__(self): return self._value 在实例上使用int函数效果很好,我认为其他内置函数都隐式依赖它,例如hex。但是,我收到以下错误消息: >>> x = MyC

我已经编写了一个类,它实现了
\uuuuu int\uuuu
方法,这样一个实例就可以像一个整数一样工作:

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
我尝试以与
\uuuu int\uuu
相同的方式实现
\uuuu hex\uuuu
方法,但没有效果


我必须做些什么才能使我的类的实例被
hex
接受?

如文档中所指定,您必须定义
\uuuu索引\uuu
方法:

hex(x)

(……)

如果
x
不是Python
int
对象,它必须定义一个返回整数的
\uuuuuuu 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'
如果您想让
十六进制(…)
的“值”是其他值,那么您可以定义
\uuuu index\uuuu
不同于
\uu int\uuuu
,尽管我强烈建议不要这样做
hex(..)
还保证它将返回一个格式正确的十六进制数字符串(
str
):例如,不能返回元组等。否则它将引发
TypeError
。例如:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __index__ returned non-int (type tuple)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:\索引\返回非int(类型元组)

如果
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。