
Question:
I have read
<ul><li><a href="https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python" rel="nofollow">What is the difference between @staticmethod and @classmethod in Python?</a> </li> <li><a href="https://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner" rel="nofollow">Python @classmethod and @staticmethod for beginner?</a></li> </ul>As staticmethod
can't access the instance of that class, I don't know what's the difference betweent it and global function
?
And when should use staticmethod
? Can give a good example?
Like global function, static method cannot access the instance of the containing class. But it conceptually belongs to the containing class. The other benefit is it can avoid name confliction.
When the function is designed to serve for some given class, it's advisable to make it as a static method of that class. This is called <a href="http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29" rel="nofollow">cohesion</a>. Besides, if this function is not used outside, you can add underscore before it to mark it as "private", this is called <a href="http://en.wikipedia.org/wiki/Information_hiding" rel="nofollow">information hiding</a>(despite Python doesn't really support private methods). As a rule of thumb, exposing as little interfaces as possible will make code more clean and less subject to change.
Even if that function is supposed to serve as a shared utility for many classes that are across multiple modules, making it a global function is still not the first choice. Consider to make it as some utility class's static method, or make it a global function in some specialized module. One reason for this is collecting similar-purposed functions into a common class or module is good for another level's abstraction/modularization(for small projects, some people may argue that this is overengineering). The other reason is this may reduce namespace pollution.
Answer2:A static method is contained in a class (adding a namespace as pointed out by @MartijnPieters). A global function is not.
Answer3:IMO it is more of a design question, rather than a technical one. If you feel that the logic belongs to a class (not the instance) add it as a staticmethod
, if it's unrelated implement it as a global function.
For example:
class Image(object):
@staticmethod
def to_grayscale(pixel):
# ...
IMO is better than
def to_grayscale(pixel):
#...
class Image(object):
# ...