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?

1
  • 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: 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. Commented Aug 12, 2021 at 3:26

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Actually, I have no idea weather I should use a static method. Maybe I should follow your advice to not use them.
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.
according to this relavant answer, I think I shouldn't make them static methods! -->They are __visualizing_debug_fucntions, which would never be used outside the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.