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

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.

主站蜘蛛池模板: 乐都县| 万宁市| 特克斯县| 台南市| 南皮县| 罗山县| 金川县| 林芝县| 酉阳| 井陉县| 额济纳旗| 平遥县| 桃园市| 托里县| 长垣县| 丹江口市| 长岭县| 侯马市| 灌南县| 濮阳县| 姜堰市| 准格尔旗| 封丘县| 黔南| 信宜市| 磴口县| 宁国市| 吕梁市| 昆明市| 阳曲县| 丰城市| 万宁市| 离岛区| 伊春市| 格尔木市| 东平县| 宾川县| 嘉荫县| 黄山市| 临沭县| 平邑县|