Does __bin__ (or __binary__) operator exists in python?
<p>In Python, the <code>__oct__</code> and <code>__hex__</code> operators exists to implement specific bahavior for <code>oct()</code> and <code>hex()</code>. See <a href="https://docs.python.org/2/reference/datamodel.html?#object.__oct__" rel="nofollow">Emulating numeric types</a></p>

<p>But I donât understand why <code>__bin__</code> (or <code>__binary__</code>) doesnât exist, whereas <code>bin()</code> function exists in the built-ins. See <a href="https://docs.python.org/2/library/functions.html#bin" rel="nofollow">Built-in Functions</a>.</p>

<p>Am I missing something? Any reason?</p>

<h2>Changes in Python 3</h2>

<p>I have found this reference <a href="https://docs.python.org/3.5/whatsnew/3.0.html?operators-and-special-methods" rel="nofollow">Operators And Special Methods</a> in "Whatâs New In Python 3.0":</p>

<blockquote>
  <p>The <strong>oct</strong>() and <strong>hex</strong>() special methods are removed â oct() and hex() use <strong>index</strong>() now to convert the argument to an integer.</p>
</blockquote>

<p>You can use <a href="https://docs.python.org/2/reference/datamodel.html?#object.__index__" rel="nofollow"><code>object.__index__</code></a> to handle <code>bin()</code> calls in Python 2. From Python 3 onwards it works for <code>hex()</code> and <code>oct()</code> as well but not in Python 2.</p>

<p>From <a href="https://docs.python.org/3/reference/datamodel.html?#object.__index__" rel="nofollow">Python 3 docs</a>:</p>

<blockquote>
  <p><code>object.__index__(self)</code></p>
  
  <p>Called to implement <code>operator.index()</code>, and whenever Python needs to
  losslessly convert the numeric object to an integer object (such as in
  slicing, or in the built-in <code>bin()</code>, <code>hex()</code> and <code>oct()</code> functions).
  Presence of this method indicates that the numeric object is an
  integer type. Must return an integer.</p>
</blockquote>

<p>It is not documented(clearly) in Python 2 but works there as well:</p>

<pre><code>&gt;&gt;&gt; class A(object):
...     def __index__(self):
...         return 100
...
&gt;&gt;&gt; bin(A())
'0b1100100'
</code></pre>

<p>The CPython code for <a href="https://hg.python.org/cpython/file/2.7/Python/bltinmodule.c#l219" rel="nofollow"><code>bin()</code></a> internally calls <a href="https://hg.python.org/cpython/file/2.7/Objects/abstract.c#l1819" rel="nofollow"><code>PyNumber_ToBase</code></a> which in turn calls <a href="https://hg.python.org/cpython/file/2.7/Objects/abstract.c#l1490" rel="nofollow"><code>PyNumber_Index</code></a> and this function invokes the <code>nb_index</code> slot on that object.</p>

python python-2.7 operators