How to create an utility class correctly [closed]

2019-02-07 18:02发布

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 class
3条回答
虎瘦雄心在
2楼-- · 2019-02-07 18:34

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

which will import your function.

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?

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.

查看更多
何必那么认真
3楼-- · 2019-02-07 18:39

Classes encapsulate both data, and behavior, so as general rules:

  • If you have something only with data, and no methods, it should probably be a namedtuple, not a class, unless you need to modify that data after creating it.
  • If a function accesses instance data, it should be a method.
  • If a function accesses no instance data, but does access class data, it should be a @classmethod.
  • If a function accesses neither instance data nor class data, it should be a standalone function, unless there's some really compelling reason to make it a @staticmethod.
  • If a class only has one method, or one method in addition to __init__(), then you almost certainly can and should rewrite it as a function.

Classes are really easy to abuse, but the temptation to shove everything into a class should really be avoided. You should use them when they make sense, and avoid using them when they don't.

查看更多
▲ chillily
4楼-- · 2019-02-07 18:46

While this question is a little opinion based, I'd say the second one is better. It reduces redundancy. Using the first method, you will have to do:

import utility
utility.utility.method1(...)

or:

from utility import utility
utility.method1(...)

Using the second one however allows you to simply do:

import utility
utility.method1(...)

or:

from utility import method1
method1(...)

If you are making a class that only contains static methods, my question is "why do you need the class?" It contributes nothing positive here.

查看更多
登录 后发表回答