1

There are two static methods in my class:

class my_class():
    def main(self, input):
        pass

    @staticmethod
    def static_1():
        #repeated_code
        pass

    @staticmethod
    def static_2():
        #repeated_code
        pass

As they share some #repeated_code, I want to reduce the repetition in them by writing a function def repeat()for the #repeated_code.

Since they are inside static methods, I couldn't call a class method via self.repeat().

It doesn't seems reasonable to write the function outside the class, because the function repeat is only used inside the class.

How should I achieve the propose of avoiding repeating myself?

zheyuanWang
  • 1,158
  • 2
  • 16
  • 30
  • 1
    I doubt it's a great idea to write your class like that. Normally, static methods are placed in a class for convenience purposes. For example, google style guide for Python recommends not using them: https://google.github.io/styleguide/pyguide.html. Why not simply create a module with these functions? You can have your `repeat()` function in the same module as well and avoid duplication. – NotAName Aug 12 '21 at 03:26

1 Answers1

1

I'm not sure this is the right way to go - static methods are meant to be small convenience functions, and if you have to share code, they aren't small.

But, if you want to, you can call a static method by referencing the class by name, like this:

class test():
    @staticmethod
    def repeat():
        # shared code
        pass

    @staticmethod
    def static_1():
        test.repeat()

    @staticmethod
    def static_2():
        test.repeat()
sj95126
  • 6,520
  • 2
  • 15
  • 34
  • Actually, I have no idea weather I should use a static method. Maybe I should follow your advice to not use them. – zheyuanWang Aug 12 '21 at 03:36
  • Well, it's a guideline, and guidelines are flexible. It may make sense to keep the code within the object, but maybe it doesn't need to be a static method. I checked the python 3.8 modules and found, for example, that ```importlib``` uses a 25-line static method with 2 inner functions, so sometimes there's use for it. – sj95126 Aug 12 '21 at 03:41
  • according to this [relavant answer](https://stackoverflow.com/questions/11788195/module-function-vs-staticmethod-vs-classmethod-vs-no-decorators-which-idiom-is), I think I shouldn't make them static methods! -->They are `__visualizing_debug_fucntions`, which would never be used outside the class. – zheyuanWang Aug 12 '21 at 03:45