the*_*orn 1 python hex magic-methods python-3.x
我有以下课程:
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)))
Run Code Online (Sandbox Code Playgroud)
在 Python 2.7 中,这会打印
(py2.7) c:\hextest> python hextest.py
0x2a
0x2a
Run Code Online (Sandbox Code Playgroud)
但在 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
Run Code Online (Sandbox Code Playgroud)
我需要实现什么才能使 Proxy 被解释为整数?
PEP3100(杂项 Python 3.0 计划)的目标之一是:
[remove]
__oct__,__hex__: 使用__index__inoct()andhex()代替。
为了使这项工作,你需要实现__index__,可能是:
def __index__(self):
# or self._value if you know _value is an integer already
return operator.index(self._value)
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看更改此行为的提交:
Run Code Online (Sandbox Code Playgroud)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.
| 归档时间: |
|
| 查看次数: |
244 次 |
| 最近记录: |