3

Consider a Python class with a number of @staticmethod methods and few instance methods. The static methods don't accept an instance of the defining class as parameters.

  • Do you think that all these static methods don't belong to the class and should be factored out?
  • If yes, which approach would you take to clean up such code?
8

Sounds like a module masquerading as a class (which is common to see in a language like Java where there are no methods outside of classes, so the only way to make something that looks like a module is to make a static only class). If the static methods are doing something that's actually related to the class as a whole, such as managing a pool of them, generating them (factories) or something along those lines then yes, they might be legitimate static methods. Otherwise, they probably should just be module level methods.

  • Even if they do work related to the class (e.g. providing a helper to instanciate the object in a different way, like SomeDataContainer.from_file), the only reason not to make it a classmethod instead is if the class is not expected to ever be subclassed. – user7043 Oct 3 '11 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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