How to do this Class inheritance in Python?
<p>I have a Python/<a href="https://github.com/tornadoweb/tornado" rel="nofollow">Tornado</a> application that responds to HTTP requests with the following 3 classes:</p>

<pre><code>import tornado.web
class MyClass1(tornado.web.RequestHandler):
    x = 1
    y = 2

    def my_method1(self):
        print "Hello World"


class MyClass2(MyClass1):

    @tornado.web.authenticated
    def get(self):
        #Do Something 1
        pass

    @tornado.web.authenticated
    def post(self):
        #Do Something 2
        pass


class MyClass3(MyClass2):
    pass
</code></pre>

<p>I would like all instances <code>MyClass2</code> to have an instance variable <code>m</code> set to the integer 3. But any instances of <code>MyClass3</code> should over-ride that and have <code>m</code> set to the integer 4. How can I do it?</p>

<p>I tried adding the following constructors to <code>MyClass2</code> and <code>MyClass3</code> respectively, but then when I try to create an instance of <code>MyClass3</code>, I get the following error: <code>TypeError: __init__() takes exactly 1 argument (3 given)</code></p>

<p>MyClass2.<strong>init</strong>():</p>

<pre><code>def __init__(self):
    self.m = 3 # This value will be overridden by a subclass
</code></pre>

<p>MyClass3.<strong>init</strong>():</p>

<pre><code>def __init__(self):
    self.m = 4
</code></pre>

<p>The <code>tornado.web.RequestHandler</code> already has a <code>__init__</code> method and Tornado expects it to take two arguments (plus the <code>self</code> argument of a bound method). Your overridden versions don't take these.</p>

<p>Update your <code>__init__</code> methods to take <em>arbitrary extra arguments</em> and pass these on via <a href="https://docs.python.org/2/library/functions.html#super" rel="nofollow"><code>super()</code></a>:</p>

<pre><code>class MyClass2(MyClass1):
    def __init__(self, *args, **kwargs):
        super(MyClass2, self).__init__(*args, **kwargs)
        self.m = 3

    @tornado.web.authenticated
    def get(self):
        #Do Something 1
        pass

    @tornado.web.authenticated
    def post(self):
        #Do Something 2
        pass


class MyClass3(MyClass2):
    def __init__(self, *args, **kwargs):
        super(MyClass3, self).__init__(*args, **kwargs)
        self.m = 4
</code></pre>

<p>You could also use the <a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.initialize" rel="nofollow"><code>RequestHandler.initialize()</code> method</a> to set up per-request instance variables; you <em>may</em> have to use <code>super()</code> again to pass on the call to the parent class, if your parent class <code>initialize()</code> does <em>more</em> work than just set <code>self.m</code>.</p>

python inheritance tornado