如何正确创建实用程序类 [英] How to create a utility class correctly
问题描述
我有一个打算用作实用程序文件的文件。
文件中应该包含很多静态方法。
I have a file that is meant to be a utility file. The file should contain a lot of static methods.
我应该这样在类内部定义方法吗?
Should I define the methods inside a class this way:
#utility.py
class utility(object):
@staticmethod
def method1(a,b,c):
pass
@staticmethod
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
,是一个第三方库,大多数Pythonista爱好者都喜欢这样做。它将良好的实用程序功能存储在单独的模块中。 此处是示例。
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屋!