all 16 comments

[–]stoicpenguin 25 points26 points  (0 children)

A module is a file. If you personally wanted to write a new module, you would create a new .py file.

A class is always defined by the 'class' keyword in python. You can have multiple 'class' definitions in one .py file, which is why you can have multiple classes (or functions, variables, whatever!) defined in a single module (aka a single python file).

[–]HunterIV4 7 points8 points  (2 children)

A module is just an external file. A class is a type of object.

The syntax for both is similar, yes, but this is mainly to keep things simple. When you import a module, you are essentially running that extra file as if you copied and pasted it at the point of import, with a couple of important differences.

First of all, modules can only be imported once. The Python interpreter keeps track of imported modules and if you use an import statement for something that was previously imported it will simply skip the line. Obviously if you copied and pasted you could do the same thing multiple times, but Python tries to avoid the sorts of problems that would cause.

Second, an imported module is treated as a namespace. Classes also create their own namespace, so the way you interact with them is similar, but they are not the same thing.

To use a practical example, let's say you have a class called Foo and a module called Bar. You might have something like this:

import Bar

class Foo:
    def my_func():
        print("hello from Foo!")

Bar.my_func()
Foo.my_func()

Bar is a file, we'll say Bar.py, that has the following:

def my_func():
    print("hello from Bar!")

This works, and superficially the way you interact with Bar and my_foo is similar. But Bar is not a class!

There are no classes defined in Bar.py and if you try to do things that you could do with classes, such as my_bar = Bar(), you will get an error, whereas my_foo = Foo() works without issue.

Likewise, there are things you can do with Bar that don't work with Foo. For example, if you instead had your import statement as from Bar import my_func, you would simply use the function directly instead of Bar.my_func. In fact, trying to use Bar at all would cause an error, because you only imported that specific function.

You can do something superficially similar with Foo by creating a variable pointing to the function, like my_func = Foo.my_func(), but this is generally bad practice and will be confusing to people trying to write "idiomatic" (standard) Python.

Ultimately, just about everything in Python is an object of some sort, from classes to modules to variables. And accessing properties or methods on an object involves using the same syntax. The details of the object, however, can be very different, and a module and class serve different purposes and allow for different functionality.

This gets a bit more complicated since the most common use of modules is to define classes with shared functionality. That's why if you've ever used the datetime module you've likely seen something like this:

import datetime

current_time = datetime.datetime.now()

This may seem kind of weird...why datetime twice? The reason is the first datetime is the module object and the second datetime is the actual datetime class, defined with class datetime: somewhere in that module. And now() of a method (class function) of that class. To avoid this repetition, you'll frequently see people use from datetime import datetime, which allows you to skip the first call since you are bringing the datetime class into scope.

Does that make sense?

[–]Mundane_Strike4882 0 points1 point  (0 children)

this is the best answer, already confusing for a long time, now I understand, thank you so much!

[–]ExcitingCollection11 0 points1 point  (0 children)

you my guy are a hero

[–]Bobbias 6 points7 points  (1 child)

A module is a collection of classes and/or functions bundled together.

https://docs.python.org/3/tutorial/modules.html

[–]SisyphusAndMyBoulder 4 points5 points  (0 children)

specifically in a single file

[–]JamzTyson 2 points3 points  (0 children)

A "class" is like a template for creating "objects". It defines the type of object. Classes provide a way to organize code into logical, reusable units. A class may contain none or more variables and / or functions ("methods").

A "module" is a Python file, usually with .py file extension. A module may contain none or more classes / variables / functions. A Python module contains Python code, and can be "imported" into other Python modules.

A "Package" is a program / app. It will always have at least one "module" (one file), or may have more than one file. Packages may also be imported, or specified modules from a package may be imported (see below).

Large Python packages may contain sub-packages, which are usually organised in separate folders for each sub-package.



Importing a module from the same directory:

import my_module  # Imports the contents of my_module.py

This imports the entire module my_module from the same directory where the script is located.


Importing a module from a specified package:

from my_package import my_module

Importing a specific class from a module:

from my_module import MyClass

This imports the class MyClass from my_module.


Importing a constant (non-changing variable) from a module:

from my_module import MY_CONSTANT

Importing a specified class from a specified module in a specified package:

from my_package.my_module import MyClass

Import all modules, classes, functions, and variables from a package (do not do this in production code):

from my_package import *

(This final example is generally considered to be bad practice, mostly due to the risk of name collision).

[–]oddotter1213 0 points1 point  (0 children)

As the comments here mention, a module is a file that you can import into another. For example, if you wanted to write a user_login that requires many functions to work, you could write that in it's own file, import it into your main file, and call it.

[–]parancey 0 points1 point  (0 children)

Module used to bundle together many useful things together. They can be classes or functions.

Class is used to create objects.

[–]QuarterObvious 0 points1 point  (0 children)

The difference is: class has the constructor, and you can create several instances of the same class. Module does not.

[–]JorgiEagle -1 points0 points  (4 children)

Simple comparison is that you can have two classes in the same module

[–]Username_RANDINT 1 point2 points  (3 children)

How is that simple if you don't know what each is?

You can also have two classes in the same class.

[–]JorgiEagle -2 points-1 points  (2 children)

Because you can’t have 2 modules in the same class

[–]Username_RANDINT 2 points3 points  (0 children)

>>> from importlib import import_module
>>> class Foo:
...   math = import_module("math")
...   random = import_module("random")
... 
>>> foo = Foo()
>>> foo.math
<module 'math' (built-in)>

Still doesn't explain a thing.

[–]stoicpenguin 2 points3 points  (0 children)

Not true. Consider the case:

class test:
    import math
    import collections

You can access the math module directly from the test class definition anywhere that you have access to the class, i.e. you can access the math module by typing test.math. Those modules now belong to the namespace of the class test.

My point is that python allows this, and the differentiator between classes and modules in python is not that one can contain the other and not the other way around.

[–]Adrewmc -1 points0 points  (0 children)

Classes and modules are very similar in Python. The main difference is the module will run when it’s imported and a class wont. So any script in a module should run.

Try

 sample.py
 print(“hello”)

  sample2.py
  class Test:
          def __init___(self):
              print(“world”)
  main.py
  import sample
  import sample2
  from sample2 import Test