0

I wasn't sure how to name the title, so if anyone knows the specific name, please correct me. Here is my situation:

class Abs(object):
    def run(self, var):
        raise NotImplementedError
class Sub1(Abs):
    def run(self, var):
        var = get_var()
        # Sub1 RUN
class Sub2(Abs):
    def run(self, var):
        var = get_var()
        #Sub2 RUN

So as you can see I have to classes that inherit from the "interface" class and both have different run function. Even though some of the run functions are different between the two, there is some similar code. (as you can see in the example) Is there any way to write the common part in the "interface" class in order to not repeat it twice?

0

2 Answers 2

2

Write the common part and put it in a new method in the base class. Consider giving it a name beginning with an underscore (the Python equivalent of protected access). Call if from each place that needs it.

class Abs(object):
    def run(self, var):
        raise NotImplementedError

    def _common_things(self,var):
        pass

class Sub1(Abs):
    def run(self, var):
        self._common_things(var)
        # etc

class Sub2(Abs):
    def run(self, var):
        self._common_things(var)
        # etc
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that's what I've ended up doing.
1

Interfaces are not supposed to implemet code but in python there are no real interfaces so it doesn't matter.

You can put var = get_var() in the base class (Abs) and then the other two method would look like this:

def run(self, var):
  super(Sub1, self).run(var)
  # Sub1 run

def run(self, var):
  super(Sub2, self).run(var)
  # Sub2 run

super() will call the code in the base class (the "interface")

3 Comments

Thank you for the quick response! I'll give this one a try. I can't see how I can use it to do the second example I gave though (the timing example), any help on that one?
Methods shouldn't time themselves. Whatever calls run should time it. You could make a method run that just times the execution and call _run and then have all the login in _run.
@lonut Thank you, that helped me a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.