Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a utility class correctly [closed]

Tags:

python

class

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 
like image 710
Weiner Nir Avatar asked Oct 27 '13 16:10

Weiner Nir


People also ask

How do you write a utility class?

Methods in the class should have appropriate names. Methods only used by the class itself should be private. The class should not have any non-final/non-static class fields. The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).

How do you create a utility in java?

I right-click 'tomcat-demo' and go to Properties. Next I go to Java Build Path and click the Projects tab. Then I click the Add... button and select the 'utility-demo' project and click OK.

How do you define a utility class in java?

utility class is a class that defines a set of methods that perform common, often re-used functions. Most utility classes define these common methods under static (see Static variable) scope. Examples of utility classes include java. util.

What type of methods are used by a utility class?

Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated. It contains a bunch of related methods, so they can be reused across the application. As an example consider Apache StringUtils, CollectionUtils or java. lang.


1 Answers

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.

like image 58
Games Brainiac Avatar answered Oct 10 '22 01:10

Games Brainiac