What's the difference to use @staticmethod and global function in Python?

ぃ、小莉子 提交于 2019-12-23 20:47:29

问题


I have read

  • What is the difference between @staticmethod and @classmethod in Python?
  • Python @classmethod and @staticmethod for beginner?

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?


回答1:


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 cohesion. Besides, if this function is not used outside, you can add underscore before it to mark it as "private", this is called information hiding(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.




回答2:


A static method is contained in a class (adding a namespace as pointed out by @MartijnPieters). A global function is not.




回答3:


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):
    # ...


来源:https://stackoverflow.com/questions/14976059/whats-the-difference-to-use-staticmethod-and-global-function-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!