hazrmard hazrmard - 1 year ago 81
Python Question

How to define and instantiate a derived class at once in python?

I have a base class that I want to derive and instantiate together. I can do that in java like:

BaseClass derivedClassInstance = new BaseClass() {
void someBaseClassMethod() { // my statements}

In python I can derive and and instantiate a base class like:

class DerivedClass(BaseClass):
def some_base_class_method():
# my statements

derived_class_instance = DerivedClass()

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

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

vz0 vz0
Answer Source

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:

>>> class BaseClass(object):
...     def f1(self, x):
...             return 2
...     def f2(self, y):
...             return self.f1(y) + y
>>> W = BaseClass()
>>> W.f2(2)
>>> X = type('DerivedClass', (BaseClass,), {'f1': (lambda self, x: (x + x))})()
>>> X.f2(2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download