覆盖 python 中的 __hex__ 3?
Overriding __hex__ in python 3?
我有以下 class:
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)))
在Python 2.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
我需要实现什么才能使 Proxy 被解释为整数?
PEP3100(其他 Python 3.0 计划)的目标之一是:
[remove] __oct__
, __hex__
: use __index__
in oct()
and hex()
instead.
要完成这项工作,您需要实施 __index__
,可能是:
def __index__(self):
# or self._value if you know _value is an integer already
return operator.index(self._value)
您可以看到更改此行为的提交 here:
r55905 | georg.brandl | 2007-06-11 10:02:26 -0700 (Mon, 11 Jun 2007) | 5 lines
Remove __oct__ and __hex__ and use __index__ for converting
non-ints before formatting in a base.
Add a bin() builtin.
我有以下 class:
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)))
在Python 2.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
我需要实现什么才能使 Proxy 被解释为整数?
PEP3100(其他 Python 3.0 计划)的目标之一是:
[remove]
__oct__
,__hex__
: use__index__
inoct()
andhex()
instead.
要完成这项工作,您需要实施 __index__
,可能是:
def __index__(self):
# or self._value if you know _value is an integer already
return operator.index(self._value)
您可以看到更改此行为的提交 here:
r55905 | georg.brandl | 2007-06-11 10:02:26 -0700 (Mon, 11 Jun 2007) | 5 lines Remove __oct__ and __hex__ and use __index__ for converting non-ints before formatting in a base. Add a bin() builtin.