1
class A():
    def __init__(self):
        self.x = 3

    @staticmethod
    def f(x):
        return x ** 2

    def g(self):
        return self.x ** 2

    def run(self):
        self.f(self.x)

    def run2(self):
        self.g()

Which one is more preferable, run() or run2? The former pass explicitly the instance variable self.x to the function f; the latter does not.

Thank you.

5
  • 2
    your x is an instance variable, so better to use run2. static methods should be only applied to work with static variables. Commented Mar 6, 2015 at 4:50
  • How about readability? It's not clear when we call the function g, what variables g is using. Commented Mar 6, 2015 at 4:51
  • better to just use g, because run2 isn't returning anything Commented Mar 6, 2015 at 4:53
  • 1
    the only useful method here is apparently g. the rest are obfuscating state for no obvious benefit Commented Mar 6, 2015 at 4:54
  • i think using f(x) is only confusing at in this example. Commented Mar 6, 2015 at 4:54

2 Answers 2

5

Since it's silly to have f() as a staticmethod, run() should almost never (if not outright never) be used.

There are (dubious) reasons to use static methods, and there are reasons to explicitly pass an instance variable to a method, but this is an example of neither.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you give an example of both, then? Thanks.
I can't give any of the first, because I don't believe that there are any. As for the second, there can be methods that use the current state for some parameters and external values for others, but sometimes we may want to use internal state for both from another method; in that case we call the method passing internal state for the external values.
1

staticmethod decorator in Python means this method could be invoked directly without initializing an instance. Static method is usually used as an common interface. But instance method can always only be used by instance itself. So when dealing with passing instance variables (self.x) to instance methods, it's better to use run2().

Comments

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.