1

I am wondering if there is a way to do what I am trying, best explained with an example:

Contents of a.py:

class A(object):
    def run(self):
        print('Original')

class Runner(object):
    def run(self):
        a = A()
        a.run()

Contents of b.py:

import a

class A(a.A):
    def run(self):
        # Do something project-specific
        print('new class')

class Runner(a.Runner):
    def other_fcn_to_do_things(self):
        pass

Basically, I have a file with some base classes that I would like to use for a few different projects. What I would like would be for b.Runner.run() to use the class A in b.py, without needing to override the run method. In the example above, I would like to code

import b
r = b.Runner()
print(r.run())

to print "new class". Is there any way to do that?

TylerH
  • 20,799
  • 66
  • 75
  • 101
kgully
  • 650
  • 7
  • 16
  • Maybe the `Runner` class constructor should accept a type and use the `run` method of whatever type it takes? – Patrick Haugh Nov 29 '16 at 18:00
  • That's a good idea, but there is already a large-ish codebase that expects a pretty specific initialization signature; I would prefer not to change that. – kgully Nov 29 '16 at 18:51

1 Answers1

-1

This seems a little convoluted. The Runner classes are probably unnecessary, unless there's something else more complex going on that was left out of your example. If you're set on not overriding the original run(), you could call it in another method in B. Please take a look at this post and this post on super().

It would probably make more sense to do something like this:

a.py:

class A(object):
    def run(self):
        # stuff
        print ('Original')

b.py:

import a

class B(A):
    def run(self):
        return super(A, self).run()
        # can also do: return A.run()

    def run_more(self):
        super(A, self).run()
        # other stuff
        print('new class')
Community
  • 1
  • 1
kimash
  • 13
  • 4