Python3: hex() on arbitrary classes

Stephen Hansen apt.shansen at gmail.com
Tue Sep 1 18:19:16 CEST 2009


On Tue, Sep 1, 2009 at 8:22 AM, Philipp Hagemeister <phihag at phihag.de>wrote:

> class X(object):
>    def __int__(self): return 42
>    def __hex__(self): return '2b' #sic
>
> hex(X())
>
>
> What would you expect? Python2 returns '2b', but python 3(74624) throws
> TypeError: 'X' object cannot be interpreted as an integer. Why doesn't
> python convert the object to int before constructing the hex string?
>

The __oct__ and __hex__ special methods were removed in 3.0; instead, it
converts the value returned by __index__ in the appropriate base.

>>> class X:
def __index__(self):
return 42

>>> hex(X())
'0x2a'

The difference between __int__ and __index__ is that the former (when called
by int()) can convert a wide range of objects into an integer even if they
really /aren't/ -- like floats. There's some numbers you want to be able to
treat as int's sometimes, and those objects should define __int__... there's
other numbers which you really want to say, 'I _am_ an integer', those
should define __index__. Anything which defines __index__ can be used in
slicing.

At least that's my understanding. It's probably only half-right / flawed,
but :) The one part I'm sure of is in Python 3, there's no methods to
explicitly convert to a non-decimal base-- you define __index__ to return
the integer value and hex()/oct()/int(X,<radix>) convert it to the
appropriate base.

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090901/2832b91e/attachment.html>


More information about the Python-list mailing list