Difference between Module and Class in Python

Can I assign value to a variable in the module? If yes, what is the difference between a class and module?

PS: I'm a Java guy (in case it helps in the way of explaining). Thanks.


There are huge differences between classes and modules in Python.

Classes are blueprints that allow you to create instances with attributes and bound functionality. Classes support inheritance, metaclasses, and descriptors.

Modules can't do any of this, modules are essentially singleton instances of an internal module class, and all their globals are attributes on the module instance. You can manipulate those attributes as needed (add, remove and update), but take into account that these still form the global namespace for all code defined in that module.

From a Java perspective, classes are not all that different here. Modules can contain more than just one class however; functions and any the result of any other Python expression can be globals in a module too.

So as a general ballpark guideline:

  • Use classes as blueprints for objects that model your problem domain.
  • Use modules to collect functionality into logical units.

Then store data where it makes sense to your application. Global state goes in modules (and functions and classes are just as much global state, loaded at the start). Everything else goes into other data structures, including instances of classes.


  • Module:

    A module is a file containing Python definitions and statements.

As the doc say.

So a module in python is simply a way to organize the code, and it contains either python classes or just functions. If you need those classes or functions in your project, you just import them. For instance, the math module in python contains just a bunch of functions, and you just call those needed (math.sin). Just have a look at this question.

On the other hand a python class is something similar to a java class, it's only structured in a slightly different way.