Python – Classes vs Modules in Python

classmodulespython

Python has many modules (such as re) that perform a specific set of actions. You can call the functions of this module and get results, and the module as a whole has an idea behind it (in this case, dealing with regular expressions).

Classes seem to do almost the exact same thing, but they also seem to use properties quite a bit more than modules.

In what ways are modules different than classes? (I know I can't subclass a module, but is that it?) When should I use a class instead of a module?

Best Answer

A python module is nothing but a package to encapsulate reusable code. Modules usually, but not always, reside in a folder with a __init__.py file inside of it. Modules can contain functions but also classes. Modules are imported using the import keyword.

Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module.

Learn more about Python modules at these links:

https://docs.python.org/2/tutorial/modules.html (Python 2) https://docs.python.org/3/tutorial/modules.html (Python 3)

Classes, in the other hand, can be defined in your main application code or inside modules imported by your application. Classes are the code of Object Oriented Programming and can contain properties and methods.

Learn more about Python classes at these links:

https://docs.python.org/2/tutorial/classes.html (Python 2) https://docs.python.org/3/tutorial/classes.html (Python 3)

Related Topic