On Tue, Sep 1, 2009 at 8:22 AM, Philipp Hagemeister <phi...@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
-- http://mail.python.org/mailman/listinfo/python-list