-1

I have a module with the class Foo. Foo has three methods:

  • The constructor(__init__())
  • An error handling method (_error_handler())
  • The method that actually does something. (run())

Then, I have a bunch of helper methods which are actually called by run(). These methods, at the time of this writing, are declared as "private" methods, that is, _helper1, _helper2...

Now my question is, such methods that are not really part of the scope of the class, should be declared as "private" methods as I'm doing right now? Or just put them outside of the class?

class Foo:
    def __init__(self)
    def _error_handler(self, error_code)
    def _helper1(self)
    def _helper2(self)
    def run(self):
        self._helper1()
        some stuff
        self._helper2()
        more stuff

Or by contrast, should my module looks like:

def _helper1()
def _helper2()

class Foo:
    def __init__(self)
    def _error_handler(self, error_code)
    def run(self):
        helper1()
        some stuff
        helper2()
        more stuff
0

This depends on the relation between the task of those methods and the purpose of the object.

If your object is a report generator and uses a lot of utility functions to justify, inflect and tabulate strings, then those methods have little to do with the purpose of the object. Generating records involves justifying lines of text, but such routines can be used for many other purposes as well, so they should live outside the class - in fact, probably within a general string-handling module.

If the methods are strongly connected to the state and member variables of the object, then they should probably be private member functions. A good heuristic is that you end up always passing some of your own member variables to a function, that function should probably be a member function itself.

0

Side from polymorphism, the difference between putting them at the module level versus the class level is really subtle. So unless you need to override these in a subclass, the answer is: it really doesn't matter much. Do what makes it the easiest to read and understand. You don't have a parameter in the module level version which would lead me to probably not put in in the class.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.