In python, is it better to define a module with functions, or a module with a class that contains functions?

In my code, either of the above two will work equally well, but I'm interested in figuring out the pros and cons of both approaches.

+3


source to share


2 answers


If functions are completely missing, a module with functions will be simpler and easier to work with.



If, on the other hand, there is an involved state, it is usually better to encapsulate that state in a class and expose the functionality through member functions.

+6


source


First of all, every thing in python is an object, so there is no significant performance difference in using functions over classes or vice versa.

If you are a beginner, then I would recommend using a module with functions, as it was simpler and easier.

The downside of this method is that you can have many functions in one module, making it difficult to keep track of and remember the functions in which modules

If you are comfortable using classes that provide the power of encapsulation (data / attributes + methods / logic) and put all logically related things in one container, a class, then you can start here.



You can customize how you want your class to interact in your code by adding: metaclasses, descriptors, and all python special functions that can override the default behavior for every part of your class.

Using classes will help you better logically represent real world problems eg. you can say i have a machine class, describe all its properties / specifications with data / attributes and define how it acts, takes input and produces output using methods. And the same can happen when you write a new protocol or standard, it's easier to represent its components / I / O / behavior with classes that can describe each of them as logical objects / containers.

Also classes are better suited for teamwork, you are not going to write everything yourself, there must be a project for your project, and this plan must be translated into smaller blocks, inputs and outputs; classes are best used in this situation.

+1


source







All Articles