lundi 11 juillet 2016

Methods intended for overriding but not part of the public API

I have a class that implements a strategy. As part of a wider strategy API it has a public interface. In this particular class the main_method applies various conditions and has a helper_... method for each condition. Thus, by subclassing and overriding these helper methods you can change the behaviour of the strategy. This is intended. However, these helper methods are not part of the API that is being implemented/exposed to the client.

It seems to me that these methods should be considered private, as they are not part of the interface that is being implemented, but on the other hand they are intended to be overridden by subclasses. In Java they would be "protected".

What's the pythonic way to deal with this situation? My code is schematically similar to the following:

class BasicFoo(Object):

    def __init__(self):
         pass

    def main_method(self, input) :
        if condition_1 :
            self._helper1(input)
        elif condition_2 :
            self._helper2(input)
        else :
            self._helper3(input)

    def _helper1(self, input)
        # do something

    def _helper2(self, input):
        # do something else

    def _helper3(self, input):
        # do something else again

class ModifiedFoo(BasicFoo):

    def __init__(self):
        super(ModifiedFoo, self).__init__()

    def _helper1(self, input):
        # a different behaviour

Aucun commentaire:

Enregistrer un commentaire