Reputation: 3223
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.
Upvotes: 1
Views: 378
Reputation: 4912
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().
Upvotes: 1
Reputation: 798686
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.
Upvotes: 5