0

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
minattosama
  • 263
  • 1
  • 9
  • The is no such things as private functions or indeed any other kind of attribute in a Python class. Naming with leading underscore is a convention but is merely a hint to the reader – DarkKnight Jan 12 '23 at 09:44
  • @Fred thanks Fred. I will change the question. I am not talking about the naming, it was just a way to explain that it will only be used inside the class – minattosama Jan 12 '23 at 09:45
  • @minattosama, how do you expect to call that function? – RomanPerekhrest Jan 12 '23 at 09:48
  • @RomanPerekhrest it will be called inside the function. Don't really mind how is called if it is OOP constructed – minattosama Jan 12 '23 at 09:50

2 Answers2

2

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
matszwecja
  • 6,357
  • 2
  • 10
  • 17
1

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.

Johan
  • 3,577
  • 1
  • 14
  • 28
  • thanks for the feedback, however the question is not about the naming but more on the construction of the class itself – minattosama Jan 12 '23 at 09:48
  • Double underscore practically prevents the function to be called from outside the class. This is the pythonic way to do it. There's no other code or syntaxic way unless you want to create some workaround hacks. – Johan Jan 12 '23 at 09:49