A module is a file containing Python definitions and statements. A module can characterize functions, classes and variables. A module can likewise incorporate runnable code. Gathering related code into a module makes the code more clear and use.
Example:
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Reloading modules in Python
reload() reloads a formerly imported module. This is helpful if we have edited the module source file using an exterior editor and want to attempt out the latest version exclusive of exit the Python interpreter. The return value is the module object.
For Python2.x
reload(module)
For above 2.x and <=Python3.3
import imp
imp.reload(module)
For >=Python3.4
import importlib
importlib.reload(module)
Import Model
As we've seen, capability is required just when you use import to bring a module overall. At the point when you utilize the from explanation, you duplicate names from the module to the importer, so the imported names are utilized without qualifying. Here are a couple of more subtleties on the import process.
Import Model Working as:
Modules are loaded and run on the first import or from.
Running a module’s code creates its top-level names.
Later import and from operations fetch an already loaded module.
Python loads, compiles and runs code in a module document just on the primary import, deliberately; since this is a costly activity, Python does it just once per process by default. Also, since code in a module is typically executed once, we can utilize it to introduce variables.
Example:
% cat simple.py
print 'hey'
maps = 1 # variable
% python
>>> import simple # first import
hey
>>> simple.maps # assignment makes an attribute
1
>>> simple.maps= 2 # modify attribute in module
>>>
>>> import simple # just fetches already-loaded module
>>> simple.maps # code wasn't rerun: attribute unaffected
2
In Above Example the print and = statements run only the first time the module is imported.
コメント