<p>I'm trying to extend some "base" classes in Python:</p>

<pre><code>class xlist (list):
    def len(self):
        return len(self)

    def add(self, *args):
        self.extend(args)
        return None


class xint (int):
    def add(self, value):
        self += value
        return self


x = xlist([1,2,3])
print x.len()   ## &gt;&gt;&gt; 3 ok
print x         ## &gt;&gt;&gt; [1,2,3] ok
x.add (4, 5, 6)
print x         ## &gt;&gt;&gt; [1,2,3,4,5,6] ok

x = xint(10)
print x         ## &gt;&gt;&gt; 10 ok
x.add (2)
print x         ## &gt;&gt;&gt; 10  # Not ok (#1)

print type(x)         ## &gt;&gt;&gt; &lt;class '__main__.xint'&gt; ok
x += 5
print type(x)         ## &gt;&gt;&gt; &lt;type 'int'&gt;  # Not ok (#2)
</code></pre>

<p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p>

<p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>

[{'answer_id': 33556, 'author': 'dwestbrook', 'author_id': 3119, 'author_profile': 'https://Stackoverflow.com/users/3119', 'pm_score': 0, 'selected': False, 'text': "<p>Ints are immutable and you can't modify them in place, so you should go with option #2 (because option #1 is impossible without some trickery).</p>\n"}, {'answer_id': 33563, 'author': 'John Douthat', 'author_id': 2774, 'author_profile': 'https://Stackoverflow.com/users/2774', 'pm_score': 4, 'selected': True, 'text': '<p><code>int</code> is a value type, so each time you do an assignment, (e.g. both instances of <code>+=</code> above), it doesn\'t modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an <code>int</code>)</p>\n<p><code>list</code> isn\'t a value type, so it isn\'t bound by the same rules.</p>\n<p>this page has more details on the differences: <a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow noreferrer">The\u202fPython Language Reference - 3.\u202fData\u202fmodel</a></p>\n<p>IMO, yes, you should define a new class that keeps an int as an instance variable</p>\n'}, {'answer_id': 33663, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 5, 'selected': False, 'text': '<p>Your two <code>xint</code> examples don\'t work for two different reasons.</p>\n\n<p>The first doesn\'t work because <code>self += value</code> is equivalent to <code>self = self + value</code> which just reassigns the local variable <code>self</code> to a different object (an integer) but doesn\'t change the original object. You can\'t really get this </p>\n\n<pre><code>&gt;&gt;&gt; x = xint(10)\n&gt;&gt;&gt; x.add(2)\n</code></pre>\n\n<p>to work with a subclass of <code>int</code> since integers are <a href="http://docs.python.org/ref/objects.html" rel="noreferrer">immutable</a>.</p>\n\n<p>To get the second one to work you can define an <a href="http://docs.python.org/ref/numeric-types.html" rel="noreferrer"><code>__add__</code> method</a>, like so:</p>\n\n<pre><code>class xint(int):\n    def __add__(self, value):\n        return xint(int.__add__(self, value))\n\n&gt;&gt;&gt; x = xint(10)\n&gt;&gt;&gt; type(x)\n&lt;class \'__main__.xint\'&gt;\n&gt;&gt;&gt; x += 3\n&gt;&gt;&gt; x\n13\n&gt;&gt;&gt; type(x)\n&lt;class \'__main__.xint\'&gt;\n</code></pre>\n'}, {'answer_id': 6809498, 'author': 'gtmanfred', 'author_id': 786635, 'author_profile': 'https://Stackoverflow.com/users/786635', 'pm_score': 2, 'selected': False, 'text': "<p>i expanded you xlist class just a bit, made it so you could find all index points of a number making it so you can extend with multiple lists at once making it initialize and making it so you can iterate through it</p>\n\n<pre><code>class xlist:\n    def __init__(self,alist):\n        if type(alist)==type(' '):\n            self.alist = [int(i) for i in alist.split(' ')]\n        else:\n            self.alist = alist\n    def __iter__(self):\n        i = 0\n        while i&lt;len(self.alist):\n            yield self.alist[i]\n            i+=1\n    def len(self):\n        return len(self.alist)\n    def add(self, *args):\n        if type(args[0])==type([1]):\n            if len(args)&gt;1:\n                tmp = []\n                [tmp.extend(i) for i in args]\n                args = tmp\n            else:args = args[0]\n        if type(args)==type(''):args = [int(i) for i in args.split(' ')] \n        (self.alist).extend(args)\n        return None\n    def index(self,val):\n        gen = (i for i,x in enumerate(self.alist) if x == val)\n        return list(gen)\n</code></pre>\n"}, {'answer_id': 71140509, 'author': 'Raphael', 'author_id': 5943840, 'author_profile': 'https://Stackoverflow.com/users/5943840', 'pm_score': 0, 'selected': False, 'text': '<p>I wrote an example of a mutable integer class that implements some basic methods from <a href="https://docs.python.org/3/library/operator.html#mapping-operators-to-functions" rel="nofollow noreferrer">the list of operator methods</a>. It can print properly, add, subtract, multiply, divide, sort, and compare equality.</p>\n<p>If you want it to do everything an int can you\'ll have to implement more methods.</p>\n<pre class="lang-py prettyprint-override"><code>class MutablePartialInt:\n    def __init__(self, value):\n        self.value = value\n\n    def _do_relational_method(self, other, method_to_run):\n        func = getattr(self.value, method_to_run)\n        if type(other) is MutablePartialInt:\n            return func(other.value)\n        else:\n            return func(other)\n\n    def __add__(self, other):\n        return self._do_relational_method(other, &quot;__add__&quot;)\n    \n    def __sub__(self, other):\n        return self._do_relational_method(other, &quot;__sub__&quot;)\n\n    def __mul__(self, other):\n        return self._do_relational_method(other, &quot;__mul__&quot;)\n    \n    def __truediv__(self, other):\n        return self._do_relational_method(other, &quot;__truediv__&quot;)\n\n    def __floordiv__(self, other):\n        return self._do_relational_method(other, &quot;__floordiv__&quot;)\n\n    def __eq__(self, other):\n       return self._do_relational_method(other, &quot;__eq__&quot;)\n    \n    def __neq__(self, other):\n       return self._do_relational_method(other, &quot;__neq__&quot;)\n\n    def __lt__(self, other):\n        return self._do_relational_method(other, &quot;__lt__&quot;)\n\n    def __gt__(self, other):\n        return self._do_relational_method(other, &quot;__gt__&quot;)\n\n    def __str__(self):\n        return str(self.value)\n\n    def __repr__(self):\n        return self.__str__()\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/33534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/394/']