How to define and instantiate a derived class at once in python?
<p>I have a base class that I want to derive and instantiate together. I can do that in java like:  </p>

<pre><code>BaseClass derivedClassInstance = new BaseClass() {
    @override
    void someBaseClassMethod() { // my statements}
};
</code></pre>

<p>In python I can derive and and instantiate a base class like:  </p>

<pre><code>class DerivedClass(BaseClass):
    def some_base_class_method():
        # my statements

derived_class_instance = DerivedClass()
</code></pre>

<p>I need to sub-class single instances of some objects with minor changes. Deriving and assigning them separately seems like overkill.  </p>

<p>Is there a Java-like <em>one-liner</em> way to derive and instantiate a class on the fly? Or is there a more concise way to do what I did in python?</p>

<p>In general you won't see this kind of code, because is difficult to read and understand. I really suggest you find some alternative and avoid what comes next. Having said that, you can create a class and an instance in one single line, like this:</p>

<pre><code>&gt;&gt;&gt; class BaseClass(object):
...     def f1(self, x):
...             return 2
...     def f2(self, y):
...             return self.f1(y) + y
... 
&gt;&gt;&gt; 
&gt;&gt;&gt; W = BaseClass()
&gt;&gt;&gt; W.f2(2)
4
&gt;&gt;&gt; X = type('DerivedClass', (BaseClass,), {'f1': (lambda self, x: (x + x))})()
&gt;&gt;&gt; X.f2(2)
6
</code></pre>

python inheritance