Every module
in python has predefined attribute ‘__name__’. If the module is being run
standalone by the user, then the module name is ‘__main__’, else it gives you
full module name.
arithmetic.py
def sum(a,b): return a+b print("Module name : ",__name__)
Run above
program you will get following output.
Module name
: __main__
test.py
import arithmetic print("Module name : ",arithmetic.__name__)
Run test.py,
you will get following output.
Module name
: arithmetic
Module name
: arithmetic
Observe the
output, module name printed twice. A module can contain executable statements.
These statements are executed; only the first time the module name is
encountered in an import statement. So executable statement in arithmetic.py is
also executed.
Update
arithmetic.py like below and rerun test.py.
def sum(a,b): return a+b if(__name__=="__main__"): print("This program is run by itslef") else: print("This module called by other module")
You will get
following output.
This module
called by other module
Module name
: arithmetic
No comments:
Post a Comment