Article Source: http://www.cnblogs.com/phinecos/archive/2010/05/07/1730027.html
When you execute the Import module, the interpreter searches for the module1.py file based on the following search path.
1) Current working directory
2) Directories in the Pythonpath
3) Python installation directory (/usr/local/lib/python)
In fact, the module search is searched in the list of directories saved in the global variable Sys.path.
Sys.path is initialized to include when the interpreter starts executing:
1) Current working directory
2) Directories in the Pythonpath
3) Python installation directory (/usr/local/lib/python)
The package is a collection of modules, and there should be a __init__.py file under the root directory of each. When the interpreter finds this file in the directory, he thinks it's a package, not an ordinary directory.
Let's illustrate this by following an example
Assume that the project structure is as follows:
demo.py
MyPackage
---classone.py
---classtwo.py
---__init__.py
Now we implement the package mechanism in two ways, the main difference is whether to write the module import statement in __init__.py.
1,__init__.py is a blank file in a way that
demo.py content is as follows:
From Mypackage.classone import Classone
From Mypackage.classtwo import Classtwo
if __name__ = = "__main__":
C1 = Classone ()
C1.printinfo ()
C2 = Classtwo ()
C2.printinfo ()
classone.py content is as follows:
Class Classone:
def __init__ (self):
Self.name = "Class One"
def printinfo (self):
Print ("I am class one!")
classtwo.py content is as follows:
Class Classtwo:
def __init__ (self):
Self.name = "Class"
def printinfo (self):
Print ("I am class two!")
2, if the import module is written in __init__.py, then the above example can be done.
The contents of __init__.py are as follows:
From Classone import Classone
From Classtwo import Classtwo
demo.py content is as follows:
Import MyPackage
if __name__ = = "__main__":
C1 = Mypackage.classone ()
C1.printinfo ()
C2 = Mypackage.classtwo ()
C2.printinfo ()
Or demo.py can also be defined as follows:
From mypackage Import *
if __name__ = = "__main__":
C1 = Classone ()
C1.printinfo ()
C2 = Classtwo ()
C2.printinfo ()
Two ways to implement the package mechanism in Python