Python3: hex() on arbitrary classes

Mark Dickinson dickinsm at gmail.com
Tue Sep 1 18:21:45 CEST 2009


On Sep 1, 4:22 pm, Philipp Hagemeister <phi... 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?

__hex__ is no longer a magic method in Python 3.  If you want to be
able to interpret instances of X as integers in the various Python
contexts that expect integers (e.g., hex(), but also things like list
indexing), you should implement the __index__ method:

Python 3.2a0 (py3k:74624, Sep  1 2009, 16:53:00)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
...     def __index__(self): return 3
...
>>> hex(X())
'0x3'
>>> range(10)[X()]
3
>>> 'abc' * X()
'abcabcabc'

--
Mark



More information about the Python-list mailing list