Python3: hex() on arbitrary classes

Philipp Hagemeister phihag at phihag.de
Tue Sep 1 12:31:41 EDT 2009


Mark Dickinson wrote:
> (...) 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:
Thanks. Somehow forgot this magic method and deleted it by accident.

Philipp
> 
> 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


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20090901/b81ee38f/attachment-0001.sig>


More information about the Python-list mailing list