<br><br><div class="gmail_quote">On Tue, Sep 1, 2009 at 8:22 AM, Philipp Hagemeister <span dir="ltr"><<a href="mailto:phihag@phihag.de">phihag@phihag.de</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">

class X(object):<br>
    def __int__(self): return 42<br>
    def __hex__(self): return '2b' #sic<br>
<br>
hex(X())<br>
<br>
<br>
What would you expect? Python2 returns '2b', but python 3(74624) throws<br>
TypeError: 'X' object cannot be interpreted as an integer. Why doesn't<br>
python convert the object to int before constructing the hex string?<br></blockquote><div><br></div><div>The __oct__ and __hex__ special methods were removed in 3.0; instead, it converts the value returned by __index__ in the appropriate base.</div>

<div><br></div><div><div>>>> class X:</div><div><span class="Apple-tab-span" style="white-space:pre">      </span>def __index__(self):</div><div><span class="Apple-tab-span" style="white-space:pre">         </span>return 42</div>

<div><br></div><div><span class="Apple-tab-span" style="white-space:pre">     </span></div><div>>>> hex(X())</div><div>'0x2a'</div><div><br></div><div>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.</div>

<div><br></div><div>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.</div>

<div><br></div><div>HTH,</div><div><br></div><div>--S</div></div></div>