Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This should do what you need:</p> <pre><code>class IntContainer(object): def __init__(self, x): self.x = x def __add__(self, other): # do some type checking on other return self.x + other def __radd__(self, other): # do some type checking on other return self.x + other </code></pre> <p>Output:</p> <pre><code>In [6]: IntContainer(3) + 6 Out[6]: 9 In [7]: 6 + IntContainer(3) Out[7]: 9 </code></pre> <p>For more information search for "radd" in the following docs:</p> <ul> <li><a href="http://docs.python.org/reference/datamodel.html#special-method-names" rel="noreferrer">http://docs.python.org/reference/datamodel.html#special-method-names</a></li> </ul> <p>You'll find other such methods for "right addition", "right subtraction", etc.</p> <p>Here's another link covering the same operators:</p> <ul> <li><a href="http://www.siafoo.net/article/57#reversed-binary-operations" rel="noreferrer">http://www.siafoo.net/article/57#reversed-binary-operations</a></li> </ul> <p>By the way, Python does have casting operators:</p> <ul> <li><a href="http://www.siafoo.net/article/57#casts" rel="noreferrer">http://www.siafoo.net/article/57#casts</a></li> </ul> <p>But, they won't accomplish what you need in your example (basically because methods don't have any type annotation for parameters, so there's no good way to cast implicitly). So you can do this:</p> <pre><code>class IntContainer2(object): def __init__(self, x): self.x = x def __int__(self): return self.x ic = IntContainer2(3) print int(ic) + 6 print 6 + int(ic) </code></pre> <p>But this will fail:</p> <pre><code>print ic + 6 # error: no implicit coercion </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload