Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
    
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 at 22:51

A python module is nothing but a package to encapsulate reusable code. Modules reside in a folder with a __init__.py file on 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 here: https://docs.python.org/2/tutorial/modules.html

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.

share|improve this answer
    
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 at 23:48
1  
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 at 2:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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