Home > Back-end >  What would be the best OOP way to create a function only used inside the class
What would be the best OOP way to create a function only used inside the class

Time:01-12

I would like to create a function that is only used as a function inside another function in the same class. My main question is, what would be the best OOP way to create this function ? Should I go as far as to use any type of decorator ; @statimethod etc

For info, it will never be used outside the class, it doesn't need any class variable used inside (so self might not be needed if we want to go with @staticmethod)

 class Awesomeness(object):
     def method(self, *args):
         self._another_method(...)
         pass

     def _another_method(self, *args):
         pass

CodePudding user response:

I see two reasonable solutions for this, each with its own ups and downs: First - static, private method:

class Awesomeness(object):
    def method(self, *args):
        self.__another_method(...)
        pass
    @staticmethod
    def __another_method(*args):
        pass

Leading double underscore causes name mangling, so outside of the class this method would have to be accessed with _Awesomeness__another_method. You can also use single underscore which just signifies it is supposed to be private, without enforcing anything.

Another solution, which works only if just one of your class methods is gonna be using this function, is to make it an inner class of this method:

class Awesomeness(object):
    def method(self, *args):
        def another_method(*args):
            pass
        another_method(...)
        pass

CodePudding user response:

The convention is to use single and double underscore as prefix for function names.

For example

class Foo:
    def _protected_function():
        ...
    
    def __private_function():
        ...

This answer explains it further.

  • Related