12

In my code either of the above two options would work equally well but I am interested in finding out the pros and cons of both approaches.

9

It honestly depends on your needs. Most of the time a module of functions will be what you're looking for.

Python classes (imho) shouldn't be thought of like classes in C# or C++ or Java, there needs to be a logical reason to group a set of functions into a larger parent, data structures would be a good example of this, you want a congruent set of functions that apply directly to the class instead of a loosely collected set of functions that are general purpose.

  • Module of Functions: general purpose, utility, and more "global" functions
  • Module of Class of Functions: grouped classes of similar needs, different linked list data types or audio processing functions or different tree types.

A module is for the overall hierarchical grouping of similar systems, I usually have all utility functions under a single module, all data under another, my data layer and connectors under a more "parent" type module. Since a module is just a mental grouping it's less about what types of systems are in it (classes or functions, honestly probably a mix of the two) and more about the logical connections between the systems under the module.

| improve this answer | |
  • 7
    I don't understand the contrast between a Python class and other languages. In what language would you have a class with with functions that have no logical reason of being grouped? – Guy Sirton Jan 26 '13 at 7:00
7

The basic question is if you need to have different instances of your module/class. a python module is like a singleton - you refer always to the same object, i.e. if you need instances, you need a class.

However, if you do not need instances you might still have the need to set up your "object" to an initial state. while this is clearly possible with a plain module, if the initializing is more complex than just setting some values, I would advice to have initializing code in a class's __init__ method for readability.

| improve this answer | |
  • 2
    it might be worth pointing out that you probably are talking about something that has state, e.g. a module with global variables vs a class with member variables. if your class only has methods but no state, there is little reason to have multiple instances – thbusch Jan 26 '13 at 11:41
  • 3
    @thbusch, yes, this is implied in needing instances. – kr1 Jan 26 '13 at 14:58
  • When you talked about the need for an instance that made me understand module vs class. Like if I needed to make multiple cars then a class would be appropriate vs a calculator module where I don't need to make a bunch of calculators I just need to use the add and subtract methods from that module. – tazboy Sep 30 '18 at 19:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.