在python 3中覆盖__hex__? [英] Overriding __hex__ in python 3?

查看:125
本文介绍了在python 3中覆盖__hex__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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中此打印

in Python 2.7 this prints

(py2.7) c:\hextest> python hextest.py
0x2a
0x2a

但是在Py3.8中,这引发了一个异常:

but in Py3.8 this raises an exception:

(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解释为整数?

what do I need to implement to make Proxy be interpreted as an integer?

推荐答案

PEP3100 (其他Python 3.0计划)旨在:

One of the goals of PEP3100 (Miscellaneous Python 3.0 Plans) was to:

[删除] __oct____hex__:在oct()hex()中使用__index__.

[remove] __oct__, __hex__: use __index__ in oct() and hex() instead.

要实现此目的,您需要实现__index__,可能是:

To make this work, you need to implement __index__, likely as:

def __index__(self):
    # or self._value if you know _value is an integer already
    return operator.index(self._value)

您可以在此处看到

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.

这篇关于在python 3中覆盖__hex__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆