How can I add to the initial definition of a python class inheriting from another class?
<p>I'm trying to define <code>self.data</code> inside a class inheriting from a class</p>

<pre><code>class Object():
    def __init__(self):
        self.data="1234"

class New_Object(Object):
    # Code changing self.data here
</code></pre>

<p>But I ran into an issue.</p>

<pre><code>class Object():
    def __init__(self):
        self.data="1234"
</code></pre>

<p>So I have the beginning class here, which is imported from elsewhere, and let's say that the class is a universal one so I can't modify the original at all.</p>

<p>In the original, the instance is referred to as "<code>self</code>" inside the class, and it is defined as self inside the definition <code>__init__</code>.</p>

<pre><code>class New_Object(Object):
    # Code changing self.data here
</code></pre>

<p>So if I wanted to inherit from the class <code>Object</code>, but define self.data inside <code>New_Object</code>, I thought I would have to define <code>__init__</code> in <code>New_Object</code>, but this overrides the <code>__init__</code> from <code>New_Object</code></p>

<p>Is there any way I could do this without copypasting the <code>__init__</code> from <code>Object</code>?</p>

<p>The answer is that you call the superclass's <code>__init__</code> explicitly during the subclass's <code>__init__</code>.   This can be done either of two ways:</p>

<pre><code>Object.__init__(self)   # requires you to name the superclass explicitly
</code></pre>

<p>or</p>

<pre><code>super(NewObject, self).__init__()   # requires you to name the subclass explicitly
</code></pre>

<p>The latter also requires you to ensure that you're using "new-style" classes: in Python 3 that's always the case, but in Python 2 you must be sure to inherit from the builtin <code>object</code> class.  In Python 3 it can actually be expressed even more simply:</p>

<pre><code>super().__init__()
</code></pre>

<p>Personally, in most of my code the "disadvantage" of having to name the superclass explicitly is no disadvantage at all, and <code>Object.__init__()</code> lends transparency since it makes it absolutely clear what is being called. This is because most of my code is single-inheritance only. The <code>super</code> route comes into its own when you have multiple inheritance. See <a href="http://stackoverflow.com/questions/222877/how-to-use-super-in-python">How to use &#39;super&#39; in Python?</a></p>

<p>Python 2 example:</p>

<pre><code>class Object(object):
    def __init__(self):
        self.data = "1234"

class NewObject:
    def __init__(self):
        # subclass-specific stuff
        super(NewObject, self).__init__()
        # more subclass-specific stuff
</code></pre>

python class inheritance instance