问题描述
我已阅读
- What is the difference between @staticmethod and @classmethod inPython?
- 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
?
什么时候应该使用 staticmethod
?可以举一个很好的例子吗?
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.
当该函数旨在用于某些给定类时,建议将其作为该类的静态方法使用。这称为。此外,如果未在外部使用此功能,则可以在其下添加下划线以将其标记为私有,这称为(尽管Python并不真正支持私有方法)。根据经验,暴露尽可能少的接口将使代码更简洁,更不会受到更改。
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.
这篇关于在Python中使用@staticmethod和global函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!