Classes vs. modules in Python

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?


A python module is nothing but a package to encapsulate reusable code. Modules usually, but not always, reside in a folder with a 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: (Python 2) (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: (Python 2) (Python 3)


If it’s a bunch of pure functions, e.g. re, I put them in a module. I use a class when I know there’s state I want to keep with that code (e.g. a file that gets read in once, but whose data is used by several of the functions).

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *