When deciding where to put helper functions the question I ask is, "Is it only for this class?" If it can help in other places, then it goes at the module level; if it is indeed only for this class, then it goes in the class with either staticmethod (needs no class data to do its job) or classmethod (uses some class, but not instance, data to do its job).
It's possible that the helper function better fits in at the module level rather than the class.
If you don't agree that this is the case, there is a staticmethod decorator that you can use on functions inside of the class. Simply put, a static method behaves the same between object instantiations of the same class. It does not rely on instance data.
For this reason, the staticmethod decorator renders behavior on the function such that it does not take an implicit first argument (typically self) as stated in the documentation).
发布评论
评论(2)
当决定在哪里放置辅助函数时,我问的问题是:“它只适用于这个类吗?”如果它可以在其他地方提供帮助,那么它就在模块级别;如果它确实只适用于此类,那么它会使用
staticmethod
(不需要类数据来完成其工作)或classmethod
(使用某些类,但是不是实例,而是完成其工作的数据)。另一个Python代码检查器是pyflakes。
When deciding where to put helper functions the question I ask is, "Is it only for this class?" If it can help in other places, then it goes at the module level; if it is indeed only for this class, then it goes in the class with either
staticmethod
(needs no class data to do its job) orclassmethod
(uses some class, but not instance, data to do its job).Another python code checker is pyflakes.
辅助函数可能更适合模块级别而不是类。
如果您不同意这种情况,可以使用 staticmethod 装饰器您可以在类内部的函数上使用它。简而言之,静态方法在同一类的对象实例化之间表现相同。它不依赖于实例数据。
因此,
staticmethod
装饰器在函数上呈现行为,使其不采用隐式第一个参数(通常为self
),如文档中所述)。It's possible that the helper function better fits in at the module level rather than the class.
If you don't agree that this is the case, there is a staticmethod decorator that you can use on functions inside of the class. Simply put, a static method behaves the same between object instantiations of the same class. It does not rely on instance data.
For this reason, the
staticmethod
decorator renders behavior on the function such that it does not take an implicit first argument (typicallyself
) as stated in the documentation).