How will you compare modules, classes and namespaces in Python?

PythonServer Side ProgrammingProgramming

Namespace is a way to implement scope. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function,  module or package is evaluated (that is, starts execution), a namespace is created. Think of it as an "evaluation context". When a function, etc., finishes execution, the namespace is dropped. The variables are dropped. Plus there's a global namespace that's used if the name isn't in the local namespace.

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. So, 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.

Classes, in the other hand, can be defined in your main application code or inside modules imported by your application. Classes are the core of Object Oriented Programming and can contain properties and methods. 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.

raja
Published on 21-Dec-2017 11:46:15
Advertisements