Pyth-我应该把我的辅助函数放在类里面还是外面?[英] Python - Should I put my helper functions inside or outside the class?

本文是小编为大家收集整理的关于Pyth-我应该把我的辅助函数放在类里面还是外面?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在Python中,如果类的某些方法需要辅助函数,但辅助函数本身并没有使用类中的任何东西,我应该将辅助函数放在类内部还是外部?

我试着把它放在里面,但是 PyLint 抱怨这个函数可以放在外面......

另外,有没有什么好书谈论这种东西(不一定是 Python)?

感谢您的帮助!

杰克

@卡尔:

该类是软件升级程序,如果该文件夹尚不存在,则辅助函数会创建一个新文件夹.该类位于一个模块中,到目前为止几乎只有该类的代码.稍后可能会添加其他类.

谢谢,杰克

推荐答案

在决定将辅助函数放在哪里时,我问的问题是,"它只适用于这个类吗?"如果它可以在其他地方提供帮助,那么它会在模块级别进行;如果它确实只用于这个类,那么它与 staticmethod (不需要类数据来完成它的工作)或 classmethod (使用一些类而不是实例数据来完成它的工作)一起进入这个类.

另一个python代码检查器是pyflakes.

本文地址:https://www.itbaoku.cn/post/627399.html

问题描述

In Python, if some methods of a class need a helper function, but the helper function itself doesn't use anything in the class, should I put the helper function inside or outside the class?

I tried putting it inside but PyLint was complaining that this function could have been put outside...

Also, are there any good books talking about this kind of stuff (it doesn't have to be Python)?

Thanks for your help!

Jack

@Karl:

The class is a software upgrader and the helper function creates a new folder if the folder doesn't exist yet. The class is in a module having pretty much only the code for the class as of now. Other classes may be added later on.

Thanks, Jack

推荐答案

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

Another python code checker is pyflakes.