0

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

BaseClass derivedClassInstance = new BaseClass() {
    @override
    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?

3
  • 3
    Consider using a tool other than inheritance for this. Maybe whatever behavior you're implementing with method overrides, you could instead pass to the parent as callbacks or something. Commented Sep 1, 2016 at 19:54
  • If BaseClass is a Template Method you won't be able to pass a callback or lambda. Commented Sep 1, 2016 at 19:56
  • @user2357112 thanks for the suggestion. I am not familiar with callbacks in python. I'll look into that. vz0's answer was a sufficient deterrent. Commented Sep 1, 2016 at 21:14

2 Answers 2

2

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)
4
>>> X = type('DerivedClass', (BaseClass,), {'f1': (lambda self, x: (x + x))})()
>>> X.f2(2)
6
Sign up to request clarification or add additional context in comments.

1 Comment

o_0 Consider me warned.
0

I think you are looking for metaclass programming.

class Base(object):
   def test(self):
      print 'hit'
a =type( 'Derived',(Base,),{})()
a.test()
hit

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.