Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Because <code>int</code> is a immutable, you cannot magically turn it into a mutable type.</p> <p>Your methods are no-ops. They change <code>self</code> in the local namespace, by reassigning it to something else. They no longer point to the instance. In other words, both methods leave the original instance <em>unaltered</em>.</p> <p>You cannot do what you want to do with a subclass of <code>int</code>. You'll have to create a custom class from scratch using the <a href="http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types" rel="nofollow">numeric type hooks</a> instead.</p> <p>Background: <code>int</code> has a <code>__new__</code> method that assigns the actual value to <code>self</code>, and there is no <code>__iadd__</code> method to support in-place adding. The <code>__init__</code> method is not ignored, but you can leave it out altogether since <code>__new__</code> already did the work.</p> <p>Assigning to <code>self</code> means you just replaced the reference to the instance with something else, you didn't <em>alter</em> anything about <code>self</code>:</p> <pre><code>&gt;&gt;&gt; class Foo(int): ... def __init__(self, value=0): ... print self, type(self) ... self = 'foobar' ... print type(self) ... &gt;&gt;&gt; foo = Foo(10) 10 &lt;class '__main__.Foo'&gt; &lt;type 'str'&gt; &gt;&gt;&gt; print foo, type(foo) 10 &lt;class '__main__.Foo'&gt; </code></pre> <p>Because <code>int</code> does not have a <code>__iadd__</code> in-place add method, your <code>self += 2</code> is interpreted as <code>self = self + 2</code> instead; again, you are assigning to <code>self</code> and replacing it with a new value altogether.</p>
    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. 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.
 

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