Implemented in two ways in python package mechanism (reprint)

 

When performing import module, the following explanation is based on the search path, the search module1.py file.

1) the current working directory

2) PYTHONPATH directories

3) Python installation directory (/ usr / local / lib / python)

In fact, the search module to search a directory listing is stored in the global variable sys.path in.

sys.path is initialized to contain at interpreter starts executing:

1) the current working directory

2) PYTHONPATH directories

3) Python installation directory (/ usr / local / lib / python)

package is a collection of modules, each root Package below should have a __init__.py file. When the interpreter found the file directory, he will think this is a Package, rather than an ordinary directory.

Let's illustrate with an example like the following

Assume that the project is structured as follows:


demo.py
MyPackage
---classOne.py
---classTwo.py
---__init__.py
       We now mechanism to implement the package in two ways, the main difference lies in whether the writing module import statements in __init__.py in.

1, __ init__.py way is a blank document,

 demo.py reads 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 reads as follows:

class classOne:
    def __init__(self):
        self.name = "class one"
   
    def printInfo(self):
        print("i am class One!")

 classTwo.py reads as follows:

class classTwo:
    def __init__(self):
        self.name = "class two"
   
    def printInfo(self):
        print("i am class two!")
       

 2, if the statement is written in the imported module __init__.py in the above examples can do this.


Wherein the __init__.py follows:

from classOne import classOne
from classTwo import classTwo


demo.py reads as follows:


import MyPackage

if __name__ == "__main__":
    c1 = MyPackage.classOne()
    c1.printInfo()
    c2 = MyPackage.classTwo()
    c2.printInfo()

Alternatively demo.py may be defined as follows:


from MyPackage import *

if __name__ == "__main__":
    c1 = classOne()
    c1.printInfo()
    c2 = classTwo()
    c2.printInfo()

Reproduced in: https: //www.cnblogs.com/licheng/archive/2010/12/06/1897421.html

Guess you like

Origin blog.csdn.net/weixin_34291004/article/details/93801092