如何正确创建实用程序类 [英] How to create an utility class correctly
问题描述
我有一个文件,意思是一个实用程序文件。
该文件应该包含许多静态方法。
I have a file that meant to be an utility file. The file should contain alot of static methods.
我应该通过这种方式定义类中的方法:
Should i define the methods inside a class this way:
#utility.py
class utility(object):
@staticmethods
def method1(a,b,c):
pass
@staticmethods
def method2(a,b,c):
pass
或者像这样使用它(没有类):
or use it like this (without a class):
#utility.py
def method1(a,b,c):
pass
def method2(a,b,c):
pass
推荐答案
第二个选项是python中的操作方式。我的意思是,如果你所做的是导入函数,那么你可以这样做:
The second option is the modus operandi in python. I mean, if all you're doing is importing functions, then you can do something like this:
from utility import some_func
这将导入您的函数。
最佳实践是,如果你只使用静态函数,那么只需将它们放在一个单独的模块的全局命名空间中,它将使你的生活更容易。你想做的是制作对象,并用静态方法填充它们。为什么要这样做,当你可以在 .py
文件中定义函数?
Best practice is, if you're using only static functions, then just put them in the global namespace of a separate module, it will make your life a lot easier. What you're trying to do is make objects and just fill them in with static methods. Why do this, when you can just define the functions in a .py
file?
尝试已完成。你试图存储一些好的效用函数。好了, python-requests
是一个第三方库,只是被大多数pythonistas所喜欢。它将其良好的效用函数存储在单独的模块中。 以下是示例
In fact, what you're trying to do has been done. You're trying to store away some good utility functions. Well, python-requests
, is a third party library that is just adored by the majority of pythonistas just does this. It stores away its good utility functions in a separate module. Here is the example.
这篇关于如何正确创建实用程序类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!