官术网_书友最值得收藏!

Python modules and packages

Any Python source file can be used as a module, and any functions and classes you define in that source file can be re-used. To load the code, the file referencing the module needs to use the import keyword. Three things happen when the file is imported:

  1. The file creates a new namespace for the objects defined in the source file.
  2. The caller executes all the code contained in the module.
  3. The file creates a name within the caller that refers to the module being imported. The name matches the name of the module.

Remember the subtract() function that you defined using the interactive shell? To reuse the function, we can put it into a file named subtract.py:

    def subtract(a, b):
c = a - b
return c

In a file within the same directory of subtract.py, you can start the Python interpreter and import this function:

    Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for
more information.
>>> import subtract
>>> result = subtract.subtract(10, 5)
>>> result
5

This works because, by default, Python will first search for the current directory for the available modules. If you are in a different directory, you can manually add a search path location using the sys module with sys.path. Remember the standard library that we mentioned a while back? You guessed it, those are just Python files being used as modules.

Packages allow a collection of modules to be grouped together. This further organizes the Python modules into a more namespace protection to further reusability. A package is defined by creating a directory with a name you want to use as the namespace, then yo can place the module source file under that directory. In order for Python to know it as a Python-package, just create a __init__.py file in this directory. In the same example as the subtract.py file, if you were to create a directory called math_stuff and create a __init__.py file:

    echou@pythonicNeteng:~/Master_Python_Networking/
Chapter1$ mkdir math_stuff
echou@pythonicNeteng:~/Master_Python_Networking/
Chapter1$ touch math_stuff/__init__.py
echou@pythonicNeteng:~/Master_Python_Networking/
Chapter1$ tree .
.
├── helloworld.py
└── math_stuff
├── __init__.py
└── subtract.py

1 directory, 3 files
echou@pythonicNeteng:~/Master_Python_Networking/
Chapter1$

The way you will now refer to the module will need to include the package name:

    >>> from math_stuff.subtract import subtract
>>> result = subtract(10, 5)
>>> result
5
>>>

As you can see, modules and packages are great ways to organize large code files and make sharing Python code a lot easier.

主站蜘蛛池模板: 鹰潭市| 白河县| 凤庆县| 曲水县| 安远县| 枣庄市| 滕州市| 靖安县| 江永县| 珲春市| 澜沧| 清苑县| 施秉县| 扶沟县| 小金县| 西城区| 乡宁县| 大渡口区| 合作市| 张北县| 彝良县| 台中县| 车险| 广灵县| 尉犁县| 都江堰市| 碌曲县| 石门县| 昭苏县| 收藏| 新乡县| 宕昌县| 福泉市| 香格里拉县| 沛县| 伊金霍洛旗| 山东| 延川县| 梓潼县| 绥棱县| 三台县|