14

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?

  • Are you aware that when you call module methods, sometimes the module is just passing through to an instance of a class? See for example the random module. I don't recall whether this is true of re, however. – Josh Caswell Aug 25 '16 at 22:51
  • 1
    A related concept to know - Module vs. Package? – RBT Jul 23 '18 at 6:05
9

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)

  • 1
    So it's not a bad thing to have a single class in a module, even if that class only has functions? I feel like in that situation I should generally just make a module without making a class. Is there an underlying rule as to when to use classes instead of modules? (That's what I'm trying to ask... Should I edit my question to make it more clear?) – Pro Q Aug 25 '16 at 23:48
  • 5
    You can create multiple instances of a class, but you cannot create instances of a module. You could compare modules to static classes or singletons. – Eneko Alonso Aug 26 '16 at 2:24
  • 1
    Modules don't always reside in a folder with a __init__.py file. – multigoodverse Dec 13 '18 at 12:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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