在Python3中重写十六进制?
我有以下课程:在Python3中重写十六进制?,python,python-3.x,hex,magic-methods,Python,Python 3.x,Hex,Magic Methods,我有以下课程: from __future__ import print_function class Proxy(object): __slots__ = ['_value'] def __init__(self, obj): self._value = obj def __hex__(self): return hex(self._value) print(hex(42)) print(hex(Proxy(42))) 在Pyt
from __future__ import print_function
class Proxy(object):
__slots__ = ['_value']
def __init__(self, obj):
self._value = obj
def __hex__(self):
return hex(self._value)
print(hex(42))
print(hex(Proxy(42)))
在Python2.7中,这将打印
(py2.7) c:\hextest> python hextest.py
0x2a
0x2a
但在Py3.8中,这引发了一个例外:
(py3.8) c:\hextest> python hextest.py
0x2a
Traceback (most recent call last):
File "hextest.py", line 14, in <module>
print(hex(Proxy(42)))
TypeError: 'Proxy' object cannot be interpreted as an integer
(py3.8)c:\hextest>python hextest.py
0x2a
回溯(最近一次呼叫最后一次):
文件“hextest.py”,第14行,在
打印(十六进制(代理(42)))
TypeError:“代理”对象不能解释为整数
我需要实现什么才能将代理解释为整数?(其他Python 3.0计划)的目标之一是:
[删除]\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
要实现这一点,您需要实现\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu索引
,可能如下所示:
def __index__(self):
# or self._value if you know _value is an integer already
return operator.index(self._value)
您可以看到更改此行为的提交:
(其他Python 3.0计划)的目标之一是:
[删除]\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
要实现这一点,您需要实现\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu索引
,可能如下所示:
def __index__(self):
# or self._value if you know _value is an integer already
return operator.index(self._value)
您可以看到更改此行为的提交:
如中所示,您应该定义\uuuuuuu索引()
。如中所示,您应该定义\uuuuuu索引()
。